USE [YrtWMS_Siemens2]
GO
/****** Object:  StoredProcedure [dbo].[sp_Purchase_Enter_NoBillEnterAndShelve_ByConsignor]    Script Date: 2022/10/18 15:03:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--*******************************************************************************
--无单扫描页面入库储存过程
  -- 增加SmallUnit字段 赋值 【Editby shaocx,2022-10-18】
--*******************************************************************************
ALTER PROCEDURE [dbo].[sp_Purchase_Enter_NoBillEnterAndShelve_ByConsignor]
    @EnterCode NVARCHAR(50),
    @ShelveCode NVARCHAR(50),
    @User_Id INT,
    @Menu_Id INT,
	@IsChecked NVARCHAR(50),
	@PrintQty INT,
    @excelDT AS [NoBillOutTable_ByConsignor11] READONLY,
    @OutMsg NVARCHAR(2000) OUTPUT
AS
BEGIN
    SET XACT_ABORT ON; --会将transcation设置为uncommittable状态，在语句块批处理结束后将回滚所有操作
    ----------读取用户信息数据--------------------
    DECLARE @UserTrueName NVARCHAR(50),
            @Dept_Id INT,
            @DeptName NVARCHAR(50),
			@UserProduct_Id INT,
			@PlatUser_Id INT,
			@PlatUserCode NVARCHAR(200),
			@PlatUserName NVARCHAR(200),
			@PlatCorpName NVARCHAR(200),
			@UserProductCode NVARCHAR(200),
			@UserProductAlias NVARCHAR(200);
    SELECT @UserTrueName = UserTrueName,
           @Dept_Id = Dept_Id,
           @DeptName = DeptName,
		   @UserProduct_Id=UserProduct_Id,
		   @PlatUser_Id=PlatUser_Id,
		   @PlatUserCode=PlatUserCode,@PlatUserName=PlatUserName, @PlatCorpName=PlatCorpName, 
		   @UserProductCode=UserProductCode, @UserProductAlias=UserProductAlias
    FROM Sys_User
    WHERE User_Id = @User_Id;

    DECLARE @Class_Id INT = 0;
    DECLARE @ClassName NVARCHAR(50) = '无单入库扫描';
    --SELECT @Class_Id = Class_Id,
    --       @ClassName = ClassName
    --FROM Base_StorageDataClass
    --WHERE Menu_Id = @Menu_Id;

    DECLARE @Storage_Id INT,
            @StorageName NVARCHAR(50),
            @PoCode NVARCHAR(50),
            @TrackingNumber NVARCHAR(50),
            @SaleCode NVARCHAR(50),
            @Quantity Decimal(18,5),
            @InProvider_Id INT,
            @InProviderCode NVARCHAR(50),
            @InProviderShortName NVARCHAR(50),
            @InConsignor_Id INT,
            @InConsignorCode NVARCHAR(50),
            @InConsignorName NVARCHAR(50),
            @LimitDate NVARCHAR(50);
    SELECT TOP 1
        @Storage_Id = Storage_Id,
        @StorageName = StorageName,
        @PoCode = PoCode,
        @TrackingNumber = TrackingNumber,
        @SaleCode = SaleCode,
		@Quantity = Quantity,
        @InProvider_Id = Provider_Id,
        @InProviderCode = ProviderCode,
        @InProviderShortName = ProviderShortName,
        @InConsignor_Id = Consignor_Id,
        @InConsignorCode = ConsignorCode,
        @InConsignorName = ConsignorName,
        @LimitDate = LimitDate
    FROM @excelDT;


    --*******************************************************************************
    --校验数据
    --*******************************************************************************
    DECLARE @Msg VARCHAR(MAX) = '',
            @Error VARCHAR(MAX) = '';
    SET @Msg = '';

    ----------验证货位是否存在------------
    SET @Msg = '';
    SELECT @Msg = @Msg + SL.PositionName + ','
    FROM @excelDT AS SL
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM dbo.Base_Position
        WHERE PositionName = SL.PositionName
              AND Storage_Id = SL.Storage_Id
    );
    IF @Msg <> ''
    BEGIN
        SET @Error = @Error + '货位：' + dbo.trim(@Msg, ',') + '不存在！';
    END;

    ----------验证供应商是否存在------------
    SET @Msg = '';
    SELECT @Msg = @Msg + P.ProductCode + ','
    FROM @excelDT AS SL
        INNER JOIN dbo.vBase_ProductInfo_SKU P
            ON SL.Product_Id = P.Product_Id
    WHERE P.Provider_Id IS NULL;

    IF @Msg <> ''
    BEGIN
        SET @Error = @Error + '' + dbo.trim(@Msg, ',') + '供应商不在不存在！';
    END;

    ----------验证拍号不能为空------------
    SET @Msg = '';
    SELECT TOP 1
        @Msg = @Msg + I.ProductCode + ','
    FROM @excelDT AS SL
        INNER JOIN dbo.vBase_ProductInfo_SKU I
            ON SL.Product_Id = I.Product_Id
    WHERE EnterMode = 'Plate' --码盘入库
          AND ISNULL(PlateCode, '') = '';
    IF @Msg <> ''
    BEGIN
        SET @Error = @Error + '商品编号：' + dbo.trim(@Msg, ',') + '拍号不能为空！';
    END;

    ----------验证拍号是否已使用------------
    SET @Msg = '';
    SELECT TOP 1
        @Msg = @Msg + SL.PlateCode + ','
    FROM @excelDT AS SL
    WHERE EnterMode = 'Plate' --码盘入库
          AND EXISTS
    (
        SELECT 1
        FROM dbo.Base_ProductPosition
        WHERE PlateCode = SL.PlateCode
              AND Storage_Id = SL.Storage_Id
              AND ProductStorage > 0
    )
          AND ISNULL(PlateCode, '') != '';
    IF @Msg <> ''
    BEGIN
        SET @Error = @Error + '拍号：' + dbo.trim(@Msg, ',') + '已使用！';
    END;

    IF (LEN(@Error) > 0)
    BEGIN
        SET @OutMsg = @Error;
        RETURN 0;
    END;
    --*******************************************************************************
    --操作入库数据
    --*******************************************************************************
    BEGIN TRAN; --开始事务

    ------操作采购入库单主表信息--------------
    DECLARE @Enter_Id INT;
    INSERT INTO Purchase_Enter
    (
        EnterCode,
        Order_Id,
        OrderCode,
        User_Id,
        UserTrueName,
        Dept_Id,
        DeptName,
        ApplyDate,
        Storage_Id,
        StorageName,
        Provider_Id,
        ProviderCode,
        ProviderShortName,
        TotalQuantity,
        TotalMoney,
        StatusID,
        StatusText,
        Auditing,
        Enable,
        Remark,
        Consignor_Id,
        ConsignorCode,
        ConsignorName,
        IsPrint,
        CreateID,
        Creator,
        CreateDate,
        OrderType,
		UserProduct_Id, PlatUser_Id,PlatUserCode, PlatUserName, PlatCorpName, UserProductCode, UserProductAlias,poCode,trackingNumber,saleCode
    )
    SELECT TOP 1
        @EnterCode,
        NULL AS Order_Id,
        NULL AS OrderCode,
        @User_Id,
        @UserTrueName,
        @Dept_Id,
        @DeptName,
        GETDATE(),
        D.Storage_Id,
        D.StorageName,
        D.Provider_Id,
        D.ProviderCode,
        D.ProviderShortName,
        0,
        0,
        1,
        '新建',
        0,
        1,
        Remark,
         D.Consignor_Id,
         D.ConsignorCode,
         D.ConsignorName,
        0,
        @User_Id,
        @UserTrueName,
        GETDATE(),
        '无单入库' AS OrderType,
		@UserProduct_Id, @PlatUser_Id,@PlatUserCode, @PlatUserName, @PlatCorpName, @UserProductCode, @UserProductAlias,@PoCode,@TrackingNumber,@SaleCode
    FROM dbo.vBase_ProductInfo_SKU P
        INNER JOIN @excelDT D
            ON D.Product_Id = P.Product_Id
    WHERE EXISTS
    (
        SELECT 1 FROM @excelDT WHERE Product_Id = P.Product_Id
    );

    SELECT @Enter_Id = SCOPE_IDENTITY(); -- IDENT_CURRENT('Purchase_Enter');

    ---对接收基础信息插入到入库单明细中-------------
    IF OBJECT_ID('tempdb..#TempDetail') IS NOT NULL
    BEGIN
        DROP TABLE #TempDetail;
    END;
    DECLARE @Product_Id BIGINT,
            @FinishedQuantity INT,
            @PositionName NVARCHAR(50),
            @ProduceDate NVARCHAR(50),
            @PurchasePrice DECIMAL(14, 2),
            @BatchNumber NVARCHAR(50),
            @PlateCode NVARCHAR(50),
			@Weight DECIMAL(14, 2),
			@TotalWeight DECIMAL(14, 2),
            @ToPlace  NVARCHAR(50),
            @ExtendField04  NVARCHAR(50),
            @FromPlace  NVARCHAR(50)
    SELECT ROW_NUMBER() OVER (ORDER BY Product_Id) AS Id,
           Product_Id,
           FinishedQuantity,
           ProduceDate,
		   LimitDate,
           PositionName,
           PurchasePrice,
           BatchNumber,
           PlateCode,
		   Weight,
		   TotalWeight,
		   Quantity,
		   ToPlace,
		   FromPlace,
		   ExtendField04
    INTO #TempDetail
    FROM @excelDT;
    DECLARE @TotalCount INT,
            @Index INT = 1;

    SELECT @TotalCount = COUNT(*)
    FROM #TempDetail;
    WHILE @Index <= @TotalCount
    BEGIN
        SELECT @Product_Id = Product_Id,
               @FinishedQuantity = FinishedQuantity,
               @ProduceDate = ProduceDate,
               @LimitDate = LimitDate,
               @PositionName = PositionName, --货位从明细中来，原来是共用的
               @PurchasePrice = PurchasePrice,
               @BatchNumber = BatchNumber,
               @PlateCode = PlateCode,
			   @Weight = Weight,
		       @TotalWeight = TotalWeight,
		       @ToPlace = ToPlace,
		       @FromPlace = FromPlace,
		       @ExtendField04 = ExtendField04
        FROM #TempDetail
        WHERE Id = @Index;

        IF (LEN(@ProduceDate) = 0)
            SET @ProduceDate = NULL;
        IF (LEN(@BatchNumber) = 0)
            SET @BatchNumber = NULL;

        -----操作入库单明细数据----------------
        INSERT INTO Purchase_EnterList
			(Enter_Id, OrderList_Id, Order_Id, Product_Id, ProductCode, ProductName, ProductModel, ProductSpec, RelationCode, 
			SmallUnit, BigUnit, Quantity, ShelveQuantity, PurchasePrice, PurchaseMoney, PositionName, PlateCode, ProduceDate, 
			BatchNumber, Enable, Remark, CreateID, Creator, CreateDate, DeclareNo, Weight, TotalWeight,OriginPlace,bigEnterQuantity,limitDate,ExtendField01,ExtendField02,ExtendField04)
		SELECT   @Enter_Id AS Expr1, 0 AS OrderList_Id, 0 AS Order_Id, P.Product_Id, P.ProductCode, P.ProductName, P.ProductModel, 
			P.ProductSpec, P.RelationCode, P.SmallUnit, P.BigUnit,D.Quantity, 0 AS Expr3, 
			@PurchasePrice AS PurchasePrice, @FinishedQuantity * @PurchasePrice AS Expr4, @PositionName AS Expr5, 
			@PlateCode AS Expr6, @ProduceDate AS Expr7, @BatchNumber AS BatchNumber, 1 AS Enable, NULL AS Remark, 
			@User_Id AS Expr8, @UserTrueName AS Expr9, GETDATE() AS Expr10, NULL AS DeclareNo, @Weight AS Weight, 
			@TotalWeight AS TotalWeight,P.OriginPlace,@FinishedQuantity,@LimitDate,@ToPlace,@FromPlace,@ExtendField04
		FROM      vBase_ProductInfo_SKU AS P INNER JOIN
			[#TempDetail] AS D ON D.Product_Id = P.Product_Id
		WHERE   (Id = @Index)

        SET @Index = @Index + 1;
    END;

    --------------------统计入库单明细表中的数据------------------------------------
    UPDATE dbo.Purchase_Enter
    SET TotalQuantity =
        (
            SELECT SUM(Quantity)
            FROM dbo.Purchase_EnterList
            WHERE Enter_Id = @Enter_Id
        ),
        TotalMoney =
        (
            SELECT SUM(PurchaseMoney)
            FROM dbo.Purchase_EnterList
            WHERE Enter_Id = @Enter_Id
        ),
		TotalWeight =
		(
		    SELECT SUM(Weight * bigEnterQuantity)
            FROM dbo.Purchase_EnterList
            WHERE Enter_Id = @Enter_Id
		),
		totalBigEnterQuantity =
		(
		    SELECT SUM(bigEnterQuantity)
            FROM dbo.Purchase_EnterList
            WHERE Enter_Id = @Enter_Id
		)
    WHERE dbo.Purchase_Enter.Enter_Id = @Enter_Id;

    --入库
    INSERT INTO dbo.Base_ProductPosition
		(Class_Id, ClassName, BillCode, MainID, DetailID, Storage_Id, StorageName, PositionName, Product_Id, ProductCode, 
		ProductName, ProductModel, InStorageDate, Provider_Id, ProviderCode, ProviderShortName, ProductStorage, 
		OrignStorage, PurchasePrice, PurchaseMoney, Rate, RatePrice, RateMoney, AvgPrice, Remark, CreateID, Creator, 
		CreateDate, SingleSignCode, Consignor_Id, ConsignorCode, ConsignorName, BatchNumber, ProduceDate, PlateCode, 
		RelationCode, ShelfLifeDay, StorageStatus, ProductAttribute, ShelfLifeDate, ValidShelfLifeDay, DeclareNo, ProductSpec, 
		UserProduct_Id, PlatUser_Id, PlatUserCode, PlatUserName, PlatCorpName, UserProductCode, UserProductAlias, 
		Weight, TotalWeight, TotalWeightOrign,OriginPlace,ContainerNo,poCode,saleCode,limitDate,extendField05,extendField07,extendField04,PartStatus,SmallUnit)
	SELECT   Class_Id, ClassName, BillCode, MainID, DetailID, Storage_Id, StorageName, PositionName, Product_Id, ProductCode, 
		ProductName, ProductModel, InStorageDate, Provider_Id, ProviderCode, ProviderShortName, ProductStorage, 
		OrignStorage, PurchasePrice, PurchaseMoney, Rate, RatePrice, RateMoney, AvgPrice, Remark, CreateID, Creator, 
		CreateDate, SingleSignCode, Consignor_Id, ConsignorCode, ConsignorName, BatchNumber, ProduceDate, PlateCode, 
		RelationCode, ShelfLifeDay, StorageStatus, ProductAttribute, DATEADD(DAY, ShelfLifeDay, ProduceDate) 
		AS ShelfLifeDate, (CASE WHEN ISNULL(ProduceDate, '') = '' THEN 0 WHEN ISNULL(ShelfLifeDay, 0) 
		= 0 THEN 0 WHEN ShelfLifeDay - DATEDIFF(DAY, ProduceDate, InStorageDate) 
		<= 0 THEN 0 ELSE ShelfLifeDay - DATEDIFF(DAY, ProduceDate, InStorageDate) END) AS ValidShelfLifeDay, DeclareNo, 
		ProductSpec, @UserProduct_Id AS Expr1, @PlatUser_Id AS Expr2, @PlatUserCode AS Expr3, 
		@PlatUserName AS Expr4, @PlatCorpName AS Expr5, @UserProductCode AS Expr6, @UserProductAlias AS Expr7, 
		Weight, TotalWeight, TotalWeightOrign,@PrintQty,ContainerNo,@poCode,@saleCode,limitDate,extendField01,extendField02,ExtendField04,@IsChecked,SmallUnit
	FROM      (SELECT   @Class_Id AS Class_Id, @ClassName AS ClassName, @EnterCode AS BillCode, M.Enter_Id AS MainID, 
		L.EnterList_Id AS DetailID, M.Storage_Id, M.StorageName, L.PositionName, L.Product_Id, L.ProductCode, 
		L.ProductName, L.ProductModel, GETDATE() AS InStorageDate, M.Provider_Id, M.ProviderCode, 
		M.ProviderShortName, L.Quantity AS ProductStorage, L.Quantity AS OrignStorage, ISNULL(L.PurchasePrice, 0) 
		AS PurchasePrice, ISNULL(L.PurchaseMoney, 0) AS PurchaseMoney, L.Rate, L.RatePrice, L.RateMoney, NULL 
		AS AvgPrice, M.Remark, L.CreateID, L.Creator, GETDATE() AS CreateDate, L.SingleSignCode, M.Consignor_Id, 
		M.ConsignorCode, M.ConsignorName, L.BatchNumber, L.ProduceDate, L.PlateCode, L.RelationCode,
			(SELECT   ISNULL(ShelfLifeDay, 0) AS Expr1
			FROM      vBase_ProductInfo_SKU
			WHERE   (Product_Id = L.Product_Id) AND (IsNeedPeriod = 1)) AS ShelfLifeDay, 
		CASE WHEN EXISTS
			(SELECT   1
			FROM      dbo.Base_Position PT
			WHERE   PT.PositionName = L.PositionName AND PT.PositionType = 4) 
		THEN '理货待上架' ELSE '正常' END AS StorageStatus, 
		CASE M.OrderType WHEN '残品预到货' THEN '残品' ELSE '正常' END AS ProductAttribute, L.DeclareNo, 
		L.ProductSpec, L.Weight, M.TotalWeight, L.TotalWeight AS TotalWeightOrign,L.ContainerNo,limitDate,extendField01,extendField02,ExtendField04,SmallUnit
	FROM      Purchase_Enter AS M INNER JOIN
		Purchase_EnterList AS L ON M.Enter_Id = L.Enter_Id
	WHERE   (M.Enter_Id = @Enter_Id) AND (L.EnterList_Id NOT IN
			(SELECT   DetailID
			FROM      Base_ProductPosition
			WHERE   (ClassName = @ClassName) AND (MainID = @Enter_Id)))) AS tbl1

    /************************************************
			--状态值或者其他操作
	*************************************************/
    --更新入库单明细状态
    UPDATE Purchase_EnterList
    SET StatusID = 2,
        StatusText = N'确认入库'
    WHERE Enter_Id = @Enter_Id AND EXISTS
    (
        SELECT 1
        FROM dbo.Base_Position P
        WHERE P.PositionName = dbo.Purchase_EnterList.PositionName AND P.PositionType = 4 /*收货位*/
    );

    UPDATE Purchase_EnterList
    SET StatusID = 5,
        StatusText = N'完全上架',
        ShelveQuantity = Quantity
    WHERE Enter_Id = @Enter_Id
          AND NOT EXISTS
    (
        SELECT 1
        FROM dbo.Base_Position P
        WHERE P.PositionName = dbo.Purchase_EnterList.PositionName AND P.PositionType = 4 /*收货位*/
    );

    --更新入库单状态
    IF EXISTS
    (
        SELECT 1
        FROM Purchase_EnterList
        WHERE Enter_Id = @Enter_Id
              AND StatusText = '确认入库'
    )
       AND EXISTS
    (
        SELECT 1
        FROM Purchase_EnterList
        WHERE Enter_Id = @Enter_Id
              AND StatusText = '完全上架'
    )
    BEGIN
        UPDATE Purchase_Enter
        SET StatusID = 4,
            StatusText = '部分上架',
            Auditor = @UserTrueName,
            Auditing = 2,
            AuditDate = GETDATE()
        WHERE (Enter_Id = @Enter_Id);
    END;
    ELSE IF EXISTS
    (
        SELECT 1
        FROM Purchase_EnterList
        WHERE Enter_Id = @Enter_Id
              AND StatusText = '完全上架'
    )
    BEGIN
        UPDATE Purchase_Enter
        SET StatusID = 5,
            StatusText = '完全上架',
            Auditor = @UserTrueName,
            Auditing = 2,
            AuditDate = GETDATE()
        WHERE (Enter_Id = @Enter_Id);

        --标注直接上架
        UPDATE Purchase_Enter
        SET Remark = '直接上架'
        FROM Purchase_Enter
            INNER JOIN dbo.Purchase_EnterList
                ON Purchase_Enter.Enter_Id = dbo.Purchase_EnterList.Enter_Id
        WHERE Purchase_Enter.Enter_Id = @Enter_Id
              AND NOT EXISTS
        (
            SELECT 1
            FROM dbo.Base_Position P
            WHERE P.PositionName = dbo.Purchase_EnterList.PositionName
                  AND P.PositionType = 4 /*收货位*/
        );
    END;
    ELSE IF EXISTS
    (
        SELECT 1
        FROM Purchase_EnterList
        WHERE Enter_Id = @Enter_Id
              AND StatusText = '确认入库'
    )
    BEGIN
        UPDATE Purchase_Enter
        SET StatusID = 2,
            StatusText = '确认入库',
            Auditor = @UserTrueName,
            Auditing = 2,
            AuditDate = GETDATE()
        WHERE (Enter_Id = @Enter_Id);
    END;

    --实时计算库存状况
    DECLARE @list NVARCHAR(4000);
    SELECT @list = LEFT(list, LEN(list) - 1)
    FROM
    (
        SELECT
            (
                SELECT CONVERT(NVARCHAR(50), Product_Id) + ','
                FROM Purchase_EnterList
                WHERE Enter_Id = @Enter_Id
                FOR XML PATH('')
            ) AS list
    ) t;
    IF @list IS NOT NULL
       AND LEN(@list) > 0
    BEGIN
        EXEC [sp_ProductInfo_Storage_RealTime] @list;
    END;

    ---------------------------------------------------
    IF @@Error <> 0
    BEGIN
        ROLLBACK TRAN;
        RETURN -1;
    END;
    ELSE
    BEGIN
        COMMIT TRAN;
        RETURN 1;
    END;
END;





