USE [Ladaer2]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE OR ALTER PROCEDURE [dbo].[sp_GetOrdersWithoutDestCashierOverview]
    @FromDate DATETIME = NULL,
    @ToDate DATETIME = NULL
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        COUNT(*) AS TotalOrders,
        ISNULL(SUM(ofin.DestFee), 0) AS TotalDestFee,
        ISNULL(SUM(ofin.Fee + ofin.PickupSubFee + ofin.DeliverySubFee + ofin.CodFee + ofin.ReturnFee + ofin.InsuranceFee - ofin.Discount), 0) AS TotalFee
    FROM [dbo].[Order] o
    INNER JOIN [dbo].[OrderFin] ofin ON o.Id = ofin.Id
    INNER JOIN [dbo].[OrderOps] ops ON o.Id = ops.Id
    WHERE ofin.PayFeeType = 2  -- ReceiverPay
        AND ops.Status = 55      -- Status = Delivered
        AND ops.PhysicalStatus = 55  -- PhysicalStatus = Delivered
        AND (ofin.DestFeeCashierId = 0 OR ofin.DestFeeCashierId IS NULL)
        AND o.IsDeleted = 0
        AND (@FromDate IS NULL OR o.CreatedTime >= @FromDate)
        AND (@ToDate IS NULL OR o.CreatedTime <= @ToDate);
END
GO
