CREATE TRIGGER [dbo].[TI_DrugH] ON [dbo].[DrugH] 
FOR INSERT
AS
 Declare @Id Bigint
 Declare @KindFlag Char(1)
 Declare @KindSave Char(1)
 Declare @Date DateTime
 Declare @SendName Varchar(35)
 Declare @ReciveName Varchar(35)
 Declare @Note Nvarchar(50)
 Declare @NoteDet  Varchar(10)
 Declare @Tarikh Smalldatetime


 Select @Id = I.Id_Havaleh , @KindFlag = i.Kind_Flag, @KindSave = i.kind_Save, @Tarikh = i.Tarikh From Inserted I

 IF @KindFlag = '1' 
 Begin
  Set @KindFlag = '7'
  Set @Note       = 'فاكتور فروش مورخ '
  Set @ReciveName = 'خريداران داروخانه'
  Set @SendName = 'انبار سطح فروش'
 End
 Else
 Begin
  Set @KindFlag = '8'
  Set @Note     = 'فاكتور برگشت فروش مورخ '
  Set @SendName = 'خريداران داروخانه'
  Set @ReciveName = 'انبار سطح فروش'
 End

 Select @Date = Convert(Varchar(10), @Tarikh, 111) 
 Select @NoteDet =  Dbo.MiladiToShamsi(@Date)
 Set @Note = @Note + @NoteDet

 IF @KindSave <> '4'
	 IF Not Exists(Select Convert(Varchar(10), Tarikh_Faktor, 111) From HeadH Where Tarikh_Faktor = @Date And Kind_Flag = @KindFlag)
	 Begin
	  Begin Tran TiDrugH
	  Insert Into Dbo.HeadH(Kind_Flag,Nu_Forosh,Nu_Bargasht_Forosh,Recive_Name,Trans_Name,Tot_Price_Forosh,Tot_kahandeh,Tot_Afzayandeh,User_Id,Tarikh_Faktor, Tarikh, Note)
	  Select @KindFlag,Nu_Forosh,Nu_Bargasht_Forosh,@ReciveName,@SendName, TotPriceForosh,TotPricekahandeh,TotPriceAfzayandeh,User_Id,@Date,  @Date, @Note From DrugH
	  Where Id_Havaleh= @Id
	  IF @@Error > 0          
		RollBack Tran TiDrugH
	  Else
		Commit Tran TiDrugH
	 End



