--msg-num = -1  برخي از کالاها ها موجودي ندارند
--msg-num = -2 موردي براي صدور وجود ندارد
--msg-num = -3 سريال کالايي که براي فروش انتخاب شده قبلا به فروش رسيده است
--msg-num = -4 انقضا کالاهائي که براي فروش انتخاب شده قبلا بع فروش رسيده است
--msg-num = -5 خطاي سيستم
-------------------------------------------------------------------------
-- مربوطه به وجه
--@Msg_Num=-10 با اين شماره موردي براي صدور وجود ندارد
------------------------------------------------------------
        

CREATE PROCEDURE [dbo].[Sodor_Factor] @msg_num Numeric(18,0) OUTPUT,@TmpId  Numeric(18,0) AS

 -----------------------------------Create Virtual TmpHeadh-------------------------------------------------------------------------
 DECLARE @TmpHeadh as Table ( Id_Havaleh  numeric(18, 0) , Kind_Flag CHAR(1) , Nu_Havaleh VARCHAR(8), Nu_Resid VARCHAR(8), Nu_Forosh VARCHAR(8),
	                          Nu_Kharid VARCHAR(8) , Nu_Bargasht_Forosh VARCHAR(8) , Nu_Bargasht_kharid VARCHAR(8),  Items SMALLINT,
	                          Recive_Name NVARCHAR(35) , Trans_Name NVARCHAR(35), Tot_Price_KHarid MONEY ,Tot_Price_forosh MONEY, Tot_Price_Omdeh MONEY, Tot_Price_Cooperative MONEY,
	                          Note NTEXT, User_id SMALLINT, Tarikh_faktor SMALLDATETIME, Tarikh_Pardakht SMALLDATETIME, CheckTarikh_Pardakht CHAR(1), Number_bar VARCHAR(15), 
	                          Sanad INT, Store_Code VARCHAR(3),  Kind_Cooperative SMALLINT
                              ) 
                              
 INSERT INTO @TmpHeadh ( Id_Havaleh , Kind_Flag  , Nu_Havaleh, Nu_Resid, Nu_Forosh  ,
	                     Nu_Kharid  , Nu_Bargasht_Forosh  ,Items ,Nu_Bargasht_kharid,
	                     Recive_Name  , Trans_Name  ,Tot_Price_KHarid,  
	                     Tot_Price_forosh , Tot_Price_Omdeh , Tot_Price_Cooperative,
	                     Note , User_id , Tarikh_faktor , Tarikh_Pardakht , CheckTarikh_Pardakht , Number_bar , 
	                     Sanad , Store_Code ,  Kind_Cooperative 
	                    )
 SELECT Id_Havaleh   , Kind_Flag  , Nu_Havaleh, Nu_Resid, Nu_Forosh  ,
	                     Nu_Kharid  , Nu_Bargasht_Forosh  ,Items ,Nu_Bargasht_kharid,
	                     Recive_Name  , Trans_Name  ,Tot_Price_KHarid,  
	                     Tot_Price_forosh , Tot_Price_Omdeh , Tot_Price_Cooperative,
	                     Note , User_id , Tarikh_faktor , Tarikh_Pardakht , CheckTarikh_Pardakht , Number_bar , 
	                     Sanad , Store_Code ,  Kind_Cooperative FROM dbo.TmpHeadH
 WHERE Id_Havaleh = @Tmpid
 
 -----------------------------------Create Virtual TmpHavaleh-------------------------------------------------------------------------
 DECLARE @TmpHavaleh as Table ( Id_Havaleh  numeric(18, 0) , AutoId bigint , Sender Varchar(5) , 
								Reciver  VARCHAR(8) , Radif  SMALLINT , K_Code  VARCHAR(15),
								K_Qty1 MONEY, K_Qty2 MONEY, R_Unit1_2 MONEY, Price_Kharid MONEY,
								Price_Forosh MONEY, Price_Omdeh MONEY, Status SMALLINT, 
								Takhfif_Flag CHAR(1), Cooperative_Flag CHAR(1), Point_Flag BIT, 
								Serial_Flag BIT, Exp_Flag BIT,Hamrah_Flag BIT, EditQty_Flag BIT, CtrMojodi CHAR(1),
								Link_Record BIGINT, Make_Flag BIT,Note NVARCHAR(60),DayOfKala SMALLINT, 
								Price_Consumer MONEY , Tot_Kharid Money, Tot_Forosh Money,  Tot_Omdeh Money
                              ) 

 INSERT INTO @TmpHavaleh ( Id_Havaleh , AutoId , Sender ,
						   Reciver , Radif ,  K_Code ,
						   K_Qty1 ,  K_Qty2 ,  R_Unit1_2 , Price_Kharid ,
						   Price_Forosh ,  Price_Omdeh ,  Status ,
						   Takhfif_Flag ,  Cooperative_Flag ,  Point_Flag , Serial_Flag, Exp_Flag,
						   Hamrah_Flag ,  EditQty_Flag , CtrMojodi ,
						   Link_Record , Make_Flag ,  Note ,  DayOfKala ,
						   Price_Consumer,  Tot_Kharid, Tot_Forosh,  Tot_Omdeh )
							
                          SELECT Id_Havaleh  , AutoId , Sender , Reciver  , Radif  , K_Code  , K_Qty1 , K_Qty2 , R_Unit1_2 , Price_Kharid ,
                          Price_Forosh , Price_Omdeh , Status , Takhfif_Flag , Cooperative_Flag , Point_Flag ,
                          Serial_Flag, Exp_Flag, Hamrah_Flag , EditQty_Flag , CtrMojodi , Link_Record , Make_Flag ,Note ,DayOfKala , 
                          Price_Consumer, Tot_Kharid, Tot_Forosh, Tot_Omdeh FROM dbo.TmpHavaleh
                          WHERE Id_Havaleh = @Tmpid
                          
						  UPDATE TmpHeadH Set 
						  Tot_Price_KHarid = T.TotPriceKharid ,
						  Tot_Price_forosh = T.TotPriceForosh ,
						  Tot_Price_Omdeh = T.TotPriceOmdeh,
						  Tot_Price_Cooperative =
						  CASE
							  WHEN Kind_Flag in (2,3,4,8)    then PriceKharidCooperative
							  When Kind_Flag in (5,7,9,0,6)  then PriceForoshCooperative
						  END ,
						  Kind_Cooperative = 
						  CASE
						    When T.KindCooperative > 0 Then Cast(Kind_Flag As TinyInt) + 900
						    ELSE 0
					      END
						  FROM @TmpHeadH TmpHeadh
						  Inner Join (
										 Select Id_Havaleh, 
										 Sum(Tot_Kharid) TotPriceKharid,      
										 Sum(Tot_Forosh) TotPriceForosh,
										 SUM(Tot_Omdeh)  TotPriceOmdeh,
										 Sum(Case When IsNull(Cooperative_Flag,0) = '1' Then Round(K_Qty1 * Price_KHarid,0) Else 0 End) PriceKharidCooperative,
										 Sum(Case When IsNull(Cooperative_Flag,0) = '1' Then Round(K_Qty1 * Price_Forosh,0) Else 0 End) PriceForoshCooperative,
										 Sum(Cast(IsNull(Cooperative_Flag,0) as int)) KindCooperative
										 From @TmpHavaleh  
										 Where Id_Havaleh = @TmpId
										 Group By Id_Havaleh
									  ) As T on Tmpheadh.Id_Havaleh  =T.Id_Havaleh      
						WHERE TmpHeadh.Id_Havaleh = @TmpId
 -----------------------------------------------------------------------------------------------------------------------------------------                         
 
 IF (SELECT TOP 1 Id_Havaleh From @TmpHavaleh Where Id_Havaleh = @TmpId) > 0     
 Begin
   set @msg_num=0
   
   -- كنترل باز بودن سند
   DECLARE @Nu_sanad BIGINT
   DECLARE @idSanad BIGINT
   DECLARE @Fiexd BIT 
   
   Select @IdSanad = Sanad From @TmpHeadH Where Id_Havaleh = @TmpId
   SELECT  @Nu_sanad =  Id_Sanad ,@Fiexd = Fiexd
   FROM   dbo.HeadS    
   WHERE  (( @idSanad IS NULL ) OR ( @idSanad = '' ) AND  DATEDIFF(DAY, Tarikh_User, GETDATE()) = 0 )  OR ( Id_Sanad = @idSanad )

   IF ( @Fiexd  = 1 )
   Begin
     Set  @msg_num= cast ('-99'+Ltrim(str(@Nu_Sanad)) as int)
     RETURN @msg_num  --msg-num = -10 سند مربوطه بسته است
   End
   ------------------------------------------------------------------------------------------------
   -- وضعيت کنترل موجودي
   IF EXISTS(
             SELECT  TOP 1 TmpHavaleh.K_Code
	  	     FROM dbo.Anbar INNER JOIN
             @TmpHavaleh AS TmpHavaleh ON dbo.Anbar.A_Code = TmpHavaleh.Sender AND dbo.Anbar.K_Code = TmpHavaleh.K_Code 
		     GROUP BY TmpHavaleh.Sender, TmpHavaleh.K_Code, dbo.Anbar.Mojodi, TmpHavaleh.CtrMojodi, TmpHavaleh.Id_Havaleh
		     HAVING  (TmpHavaleh.CtrMojodi = '1') AND (TmpHavaleh.Id_Havaleh = @tmpid) 
		     AND (dbo.Anbar.Mojodi - SUM(TmpHavaleh.K_Qty1) < 0) And ( Len(TmpHavaleh.Sender) =3)
            ) 
   BEGIN
      Set  @msg_num=-1  --msg-num = -1  برخي از کالاها ها موجودي ندارند
      RETURN @msg_num
   END
   
   ------------------------------------------------------------------------------------------------
   -- کنترل سريال
   Else IF (Select Count(*) from LESS_Serial(@TmpId))  > 0 
   Begin
     Set  @msg_num=-3 --msg-num = -3 سريال کالايي که براي فروش انتخاب شده قبلا به فروش رسيده است
     RETURN @msg_num
   End
   ------------------------------------------------------------------------------------------------
   -- کنترل تارخ انقضا
   Else IF (Select Count(*) from LESS_Exp(@TmpId))  > 0 
   Begin
     Set  @msg_num=-4 --msg-num = -4 انقضا کالاهائي که براي فروش انتخاب شده قبلا به فروش رسيده است
     RETURN @msg_num
   End
   
   ------------------------------------------------------------------------------------------------
   Else 
   Begin   
     Begin Tran 
     Declare @Last_Id Numeric(18,0)
     Insert Into Dbo.HeadH(Kind_Flag,Nu_Havaleh,Nu_Resid,Nu_Forosh,Nu_Kharid,Nu_Bargasht_Forosh,Nu_Bargasht_kharid,Items,Recive_Name,Trans_Name,Tot_Price_kharid,Tot_Price_Forosh,Tot_Price_Omdeh,Tot_Price_Cooperative, Note,User_Id,Tarikh_Faktor, Tarikh_Pardakht, CheckTarikh_Pardakht, Number_Bar, Sanad,Store_Code, Kind_Cooperative)
                    Select Kind_Flag,Nu_Havaleh,Nu_Resid,Nu_Forosh,Nu_Kharid,Nu_Bargasht_Forosh,Nu_Bargasht_kharid,Items,Recive_Name,Trans_Name,Tot_Price_kharid,Tot_Price_Forosh,Tot_Price_Omdeh,Tot_Price_Cooperative, Note,User_Id,Tarikh_Faktor,Tarikh_Pardakht, CheckTarikh_Pardakht ,Number_Bar, Sanad, Store_code,Kind_Cooperative  From @TmpHeadH
                    Where Id_Havaleh=@TmpId	
     IF @@Error > 0  
     Begin
       Set  @msg_num=-5  
       ROLLBACK TRANSACTION 
       RETURN @msg_num 
     End    
   
     Select @Last_Id=Scope_Identity() 
   
     
     INSERT Into Dbo.Havaleh(Id_Havaleh,AutoId,Sender,Reciver,Radif,K_Code,K_Qty1,K_Qty2,R_Unit1_2,Price_Kharid,Price_Forosh,Price_Omdeh,Status,Takhfif_Flag,Cooperative_Flag, Point_Flag,Serial_Flag,Hamrah_Flag,EditQty_Flag,CtrMojodi,Link_Record,Exp_Flag,Make_Flag,Note,DayOfKala, Price_Consumer)
                     Select @Last_Id ,AutoId,Sender,Reciver,Radif,K_Code,K_Qty1,K_Qty2,R_Unit1_2,Price_Kharid,Price_Forosh,Price_Omdeh,Status,Takhfif_Flag,Cooperative_Flag, Point_Flag,Serial_Flag,Hamrah_Flag,EditQty_Flag,CtrMojodi,Link_Record,Exp_Flag,Make_Flag,Note,DayOfKala,Price_Consumer
                     From @TmpHavaleh Where Id_Havaleh=@TmpId  -- رکوردهاي جدول تمپ را به جدول اصلي حواله اضافه ميکند
   
     IF @@Error > 0  
     Begin
       Set  @msg_num=-5  
       ROLLBACK TRANSACTION
       RETURN @msg_num 
     End    
     ------------------------------------------------------------------------------------------------    -- صدور تاريخ انقضا
     IF ( Select TOP 1 Id_Havaleh From @TmpHavaleh WHERE (Id_Havaleh = @TmpId) AND (Exp_Flag = 1) ) > 0
        Exec Sodor_Exp @TmpId  
     IF @@Error > 0  
     Begin
       Set  @msg_num=-5  
       ROLLBACK TRANSACTION
       RETURN @msg_num 
     End    
     ------------------------------------------------------------------------------------------------
     IF (Select TOP 1 Id_Serial  FROM  dbo.TmpSerial WHERE  AutoId In (Select  AutoId From @TmpHavaleh Where Id_Havaleh = @TmpId)) > 0 
       exec  Sodor_Serial  @TmpId  
     IF @@Error > 0  
     Begin
       Set  @msg_num=-5  
       ROLLBACK TRANSACTION
       RETURN @msg_num 
     End    
     ------------------------------------------------------------------------------------------------
     Delete from dbo.Tmp_Over_Under_Factor Where  (Id_Havaleh=@TmpId) And (Price <=0 Or Price is null )
     IF (SELECT TOP 1 Id_Havaleh  FROM dbo.Tmp_Over_Under_Factor WHERE (Id_Havaleh = @TmpId)) > 0 
     BEGIN
       INSERT Into dbo.Over_Under_Factor(Id_Havaleh, Code_Over_Under ,Type ,Price ,[Percent] , Act_Code , Auto_Id_Havaleh , Price_Row, Guy_Code)
                            SELECT @Last_Id, Code_Over_Under ,Type ,Price , [Percent] , Act_Code , Auto_Id_Havaleh , Price_Row, Guy_Code
                            FROM Tmp_Over_Under_factor  Where (Id_Havaleh=@TmpId)      
       IF @@Error > 0 
       Begin
         Set  @msg_num=-5  
         ROLLBACK TRANSACTION
         RETURN @msg_num 
       End    
     End
     
     ------------------------------------------------------------------------------------------------
     Insert Into Dbo.Over_Under_Row (AutoId,name,Code_Act,Type,Price,[Percent],Code_Over_Under)
     SELECT  Tmp_Over_Under_Row.AutoId, Tmp_Over_Under_Row.name, Tmp_Over_Under_Row.Code_Act, 
                   Tmp_Over_Under_Row.Type, Tmp_Over_Under_Row.Price, Tmp_Over_Under_Row.[Percent], 
                   Tmp_Over_Under_Row.Code_Over_Under FROM  @TmpHavaleh TmpHavaleh  INNER JOIN
                   Tmp_Over_Under_Row ON TmpHavaleh.AutoId = Tmp_Over_Under_Row.AutoId
                    WHERE  TmpHavaleh.Id_Havaleh = @TmpId And Price > 0 
     IF @@Error > 0  
     Begin
       Set  @Msg_Num= -5  
       ROLLBACK TRANSACTION
       RETURN @Msg_Num 
     End
      ---------------------------------------------------------------------------------------------------------------------------------------
     Declare @Id_Cheqe BigInt      
     SELECT  @Id_cheqe= dbo.TmpHeadC.Id_Cheqe
     FROM dbo.TmpHeadC INNER JOIN dbo.TmpCheqe ON dbo.TmpHeadC.Id_Cheqe = dbo.TmpCheqe.Id_Cheqe
     WHERE (dbo.TmpHeadc.Id_Havaleh = @TmpId)And (dbo.TmpCheqe.CH_Price > 0)
  
     IF  (@Id_Cheqe <> Null) Or (@Id_Cheqe <> 0) 
       Exec  @Msg_Num=Sodor_Vajeh  @Msg_num,@Id_Cheqe,@TmpId,@last_id,@IdSanad
     IF @Msg_Num < 0  
     Begin
       Set  @msg_num=-5  
       ROLLBACK TRANSACTION
       RETURN @msg_num 
     End    
     ------------------------------------------------------------------------------------------------
     Delete From dbo.TmpHeadH  Where  Id_Havaleh=@TmpId 
     ------------------------------------------------------------------------------------------------
     Commit Tran
     SELECT @msg_num=@Last_Id
     RETURN @msg_num
     print 'فاکتور صادر شد' 
  End 
 End 
 Else 
 Begin
  Set  @msg_num=-2 
  RETURN @msg_num
  Print 'موردي براي صدور وجود ندارد'
 END
