-- 安全删除方式（推荐）
IF OBJECT_ID('dbo.ZZV_FaHuo', 'V') IS NOT NULL
    DROP VIEW dbo.ZZV_FaHuo;
GO

CREATE VIEW ZZV_FaHuo AS

/*2025-08-13调整发货数量逻辑"销售订单发货数量取数逻辑，要根据销售订单行数据进行判断：
1、如果行在云星空没有关联发货通知单，就取该行关联的中间表发货数量
2、如果行在云星空有关联发货通知单，就取该行关联的云星空发货数量+关联的中间表（销售出库数量+其他出库数量）"*/
SELECT 
    salorder.FID AS 销售订单FID,
    salorderitem.FENTRYID AS 销售订单FENTRYID,
    salorder.F_CONTRACTNUMBER AS 合同号,
    yun.[云星空发货数量],
    yun.[云星空发货金额(原币)],
   CASE WHEN  yun.[云星空发货数量] IS  NULL  THEN  k3order.发货数量 ELSE ISNULL( k3order.销售出库数量,0)+ ISNULL( k3order.其他出库数量,0) END [k3发货数量],
    CASE WHEN  yun.[云星空发货数量] IS  NULL  THEN  k3order.发货金额 ELSE (ISNULL( k3order.销售出库数量,0)+ ISNULL( k3order.其他出库数量,0))* ISNULL(k3order.含税单价,0) END  [k3发货金额],
	 k3order.发货金额 AS [原K3发货金额],

    k3order.含税单价,
	k3order.退货数量,
	k3order.退货金额
FROM 
    dbo.T_SAL_ORDER salorder
LEFT JOIN T_SAL_ORDERENTRY salorderitem ON salorder.FID = salorderitem.FID
LEFT JOIN (
    SELECT 
        c.FSBILLID,
        c.FSID,
        SUM(B.FQTY) AS [云星空发货数量],
        SUM(B_F.FAllAmount) AS [云星空发货金额(原币)]
    FROM
        T_SAL_DELIVERYNOTICEENTRY_LK C
    LEFT JOIN T_SAL_DELIVERYNOTICEENTRY B ON B.FENTRYID = C.FENTRYID AND C.FSTABLENAME = 'T_SAL_ORDERENTRY'
    LEFT JOIN T_SAL_DELIVERYNOTICE A ON A.FID = B.FID AND A.FDOCUMENTSTATUS = 'C'
    LEFT JOIN T_SAL_DELIVERYNOTICEENTRY_F B_F ON B.FENTRYID = B_F.FENTRYID
    WHERE C.FSTABLENAME = 'T_SAL_ORDERENTRY' AND A.FDOCUMENTSTATUS = 'C' 
    GROUP BY c.FSBILLID, c.FSID,a.F_PAPERCONTRACT
) yun ON yun.FSBILLID = salorder.FID AND yun.FSID = salorderitem.FENTRYID
LEFT JOIN [oldk3seorder0701] k3order 
    ON salorderitem.F_K3SEQ = k3order.行号 AND salorder.FBILLNO = k3order.[单据编码]
WHERE 
    salorder.FDOCUMENTSTATUS = 'C'
