USE [Ladaer2]
GO
/****** Object:  StoredProcedure [dbo].[MobileApp_Driver_GetDashboard]    Script Date: 3/5/2026 1:40:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		thangtq
-- Create date: <Create Date,,>
-- Description:	Lay cac thong tin dashboard cua mobile app lai xe
-- =============================================
ALTER PROCEDURE [dbo].[MobileApp_Driver_GetDashboard]
	@UserId INT
AS
BEGIN
	SET NOCOUNT ON;

    DECLARE @CurrentDate DATE = GETDATE();

    SELECT 
        -- Pickup Orders
        SUM(CASE WHEN (oops.[Status] IN (1, 3) AND oops.PhysicalStatus IN (12, 13)) THEN 1 ELSE 0 END) AS TotalPickupOrders,
        SUM(CASE WHEN (oops.[Status] = 3 AND oops.PhysicalStatus = 13) THEN 1 ELSE 0 END) AS PickedupOrders,
        SUM(CASE WHEN (oops.[Status] = 1 AND oops.PhysicalStatus = 12) THEN 1 ELSE 0 END) AS PickingupOrders,
        
        -- Delivery Orders (chỉ đếm đơn đã giao trong ngày hôm nay dựa trên DeliveryDate)
        SUM(CASE WHEN (oops.[Status] = 3 AND oops.PhysicalStatus = 53)
                 OR   (oops.[Status] = 55 AND oops.PhysicalStatus = 55 
                       AND CAST(ott.DeliveryDate AS DATE) = @CurrentDate)
             THEN 1 ELSE 0 END) AS TotalDeliveryOrders,
        SUM(CASE WHEN (oops.[Status] = 55 AND oops.PhysicalStatus = 55 
                       AND CAST(ott.DeliveryDate AS DATE) = @CurrentDate)
             THEN 1 ELSE 0 END) AS DeliveredOrders,
        SUM(CASE WHEN (oops.[Status] = 3 AND oops.PhysicalStatus = 53) THEN 1 ELSE 0 END) AS DeliveryingOrders,

		-- Tổng SourceFee user đang cầm
    (SELECT ISNULL(SUM(SourceFee), 0)
     FROM [OrderFin]
     WHERE SourceFeeCashierId = @UserId AND IsDeleted = 0
    ) AS TotalSourceFee,

    -- Tổng DestFee user đang cầm
    (SELECT ISNULL(SUM(DestFee), 0)
     FROM [OrderFin]
     WHERE DestFeeCashierId = @UserId AND IsDeleted = 0
    ) AS TotalDestFee,

    -- Tổng CollectAmount (COD) user đang cầm
    (SELECT ISNULL(SUM(CollectAmount), 0)
     FROM [OrderFin]
     WHERE CodCashierId = @UserId AND IsDeleted = 0
    ) AS TotalCollectAmount


    FROM 
        [OrderOps] oops
    LEFT JOIN [OrderTimeTrack] ott ON oops.Id = ott.Id
    WHERE 
        oops.PicId = @UserId
		AND oops.IsDeleted = 0
        AND oops.PhysicalStatus NOT IN (8) -- Exclude cancelled orders
END
