 CREATE TABLE [dbo].[ISOBIRIM](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[eFaturaTip] int NULL,
	[IsoBirimKodu] [nvarchar](20) NULL,
	[IsoBirimAdi] [nvarchar](50) NULL
 CONSTRAINT [PK_ISOBIRIM] PRIMARY KEY CLUSTERED 
(
	Id ASC
)
)
end
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
             				  
 if  not  exists (select * from dbo.syscolumns where id = object_id(N'AnaMenuAyar') and name=N'Varsayilan')
begin
ALTER TABLE AnaMenuAyar ADD Varsayilan bit
end
else begin
ALTER TABLE AnaMenuAyar alter column Varsayilan bit
end
go--
-------------------------------------------------------------------------------------------------------------------------------------------
             				  
if  not  exists (select * from dbo.syscolumns where id = object_id(N'STOKKARTI') and name=N'IkinciBirimBarkodu')
begin
	ALTER TABLE STOKKARTI ADD IkinciBirimBarkodu nvarchar(40)
end ELSE BEGIN
	ALTER TABLE STOKKARTI ALTER COLUMN IkinciBirimBarkodu nvarchar(40)
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 if  not  exists (select * from dbo.syscolumns where id = object_id(N'STOKKARTI') and name=N'UcuncuBirimBarkodu')
begin
	ALTER TABLE STOKKARTI ADD UcuncuBirimBarkodu nvarchar(40)
end ELSE BEGIN
	ALTER TABLE STOKKARTI ALTER COLUMN UcuncuBirimBarkodu nvarchar(40)
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 if  not  exists (select * from dbo.syscolumns where id = object_id(N'STOKKARTI') and name=N'DorduncuBirimBarkodu')
begin
	ALTER TABLE STOKKARTI ADD DorduncuBirimBarkodu nvarchar(40)
end ELSE BEGIN
	ALTER TABLE STOKKARTI ALTER COLUMN DorduncuBirimBarkodu nvarchar(40)
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 if  not  exists (select * from dbo.syscolumns where id = object_id(N'STOKKARTI') and name=N'BesinciBirimBarkodu')
begin
	ALTER TABLE STOKKARTI ADD BesinciBirimBarkodu nvarchar(40)
end ELSE BEGIN
	ALTER TABLE STOKKARTI ALTER COLUMN BesinciBirimBarkodu nvarchar(40)
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 if  not  exists (select * from dbo.syscolumns where id = object_id(N'STOKKARTI') and name=N'AltinciBirimBarkodu')
begin
	ALTER TABLE STOKKARTI ADD AltinciBirimBarkodu nvarchar(40)
end ELSE BEGIN
	ALTER TABLE STOKKARTI ALTER COLUMN AltinciBirimBarkodu nvarchar(40)
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
             				  
if exists (select * from sys.views where name='V_StokBarkodlari_Birimler')
drop VIEW V_StokBarkodlari_Birimler
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE  VIEW V_StokBarkodlari_Birimler AS  
select   
 StokKodu,  
 (Select Barkodu from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 2) IkinciBirimBarkodu,  
 (Select Carpani from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 2) IkinciBirimCarpani,  
 (Select Birim from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 2) IkinciBirim,  
 (Select Barkodu from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 3) UcuncuBirimBarkodu, 
 (Select Carpani from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 3) UcuncuBirimCarpani,  
 (Select Birim from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 3) UcuncuBirim,   
 (Select Barkodu from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 4) DorduncuBirimBarkodu, 
 (Select Carpani from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 4) DorduncuBirimCarpani,  
 (Select Birim from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 4) DorduncuBirim,   
 (Select Barkodu from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 5) BesinciBirimBarkodu, 
 (Select Carpani from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 5) BesinciBirimCarpani,  
 (Select Birim from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 5) BesinciBirim,   
 (Select Barkodu from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 6) AltinciBirimBarkodu,   
  (Select Carpani from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 6) AltinciBirimCarpani,  
 (Select Birim from StokBarkodlari sb1 where sb1.StokKodu  =sb.StokKodu and SiraNo = 6) AltinciBirim
from StokBarkodlari sb  
Group By StokKodu 
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if exists (select * from sys.procedures where name='sp_BirimBarkod_Aktarim')
drop proc sp_BirimBarkod_Aktarim
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE sp_BirimBarkod_Aktarim AS
UPDATE sk SET sk.IkinciBirim = ISNULL(Brm.IkinciBirim,sk.IkinciBirim),
			  sk.IkinciBirimBarkodu = ISNULL(Brm.IkinciBirimBarkodu,sk.IkinciBirimBarkodu),
			  sk.IkinciBirimMiktari = ISNULL(Brm.IkinciBirimCarpani,sk.IkinciBirimMiktari),
			  sk.UcuncuBirim = ISNULL(Brm.UcuncuBirim,sk.UcuncuBirim),
			  sk.UcuncuBirimBarkodu = ISNULL(Brm.UcuncuBirimBarkodu,sk.UcuncuBirimBarkodu),
			  sk.UcuncuBirimMiktari = ISNULL(Brm.UcuncuBirimCarpani,sk.UcuncuBirimMiktari),
			  sk.DorduncuBirim = ISNULL(Brm.DorduncuBirim,sk.DorduncuBirim),
			  sk.DorduncuBirimBarkodu = ISNULL(Brm.DorduncuBirimBarkodu,sk.DorduncuBirimBarkodu),
			  sk.DorduncuBirimMiktari = ISNULL(Brm.DorduncuBirimCarpani,sk.DorduncuBirimMiktari),
			  sk.BesinciBirim = ISNULL(Brm.BesinciBirim,sk.BesinciBirim),
			  sk.BesinciBirimBarkodu = ISNULL(Brm.BesinciBirimBarkodu,sk.BesinciBirimBarkodu),
			  sk.BesinciBirimMiktari = ISNULL(Brm.BesinciBirimCarpani,sk.BesinciBirimMiktari),
			  sk.AltinciBirim = ISNULL(Brm.AltinciBirim,sk.AltinciBirim),
			  sk.AltinciBirimBarkodu = ISNULL(Brm.AltinciBirimBarkodu,sk.AltinciBirimBarkodu),
			  sk.AltinciBirimMiktari = ISNULL(Brm.AltinciBirimCarpani,sk.AltinciBirimMiktari)
  from STOKKARTI sk,
       V_StokBarkodlari_Birimler Brm
 where sk.Kodu = Brm.StokKodu 
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
DELETE FROM GridView where KayitIsmi = 'FrmHizliPerakendePCTSPanel9pcHizliSatistsSatiscxHareketlertvHareketler'
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if NOT  exists (select * from sys.tables where name='ISOBIRIM')
BEGIN
CREATE TABLE [dbo].[ISOBIRIM](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[eFaturaTip] int NULL,
	[IsoBirimKodu] [nvarchar](20) NULL,
	[IsoBirimAdi] [nvarchar](50) NULL
 CONSTRAINT [PK_ISOBIRIM] PRIMARY KEY CLUSTERED 
(
	Id ASC
)
)
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if  not  exists (select * from dbo.syscolumns where id = object_id(N'ISOBIRIM') and name=N'eFaturaTip')
begin
	ALTER TABLE ISOBIRIM ADD eFaturaTip int
end ELSE BEGIN
	ALTER TABLE ISOBIRIM ALTER COLUMN eFaturaTip int
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if exists (select * from sys.procedures where name='spTahsilVadeRaporu_Rut')
drop proc spTahsilVadeRaporu_Rut
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

create proc spTahsilVadeRaporu_Rut (@RutAdi nvarchar(max),@RutGunu nvarchar(max),@RutSatici nvarchar(max))    
as      
create table #odeme      
(      
  RecID integer Identity (1, 1) not null, NoId integer, IslemNo integer, Tarih datetime,      
  CariNo integer,  IslemTuru nvarchar(20) COLLATE DATABASE_DEFAULT,  Bakiye float,  Borc_Kullanilan float ,  Devreden float,  Borc float,      
  Devir float  PRIMARY KEY CLUSTERED  (RecID)      
)      
    
DECLARE @CariNo int    
Declare @DagitimTutari float      
Declare @NoId integer,  @IslemNo integer,  @Tarih datetime,  @Borc decimal (28, 14), @Borc_Kullanilan decimal (28, 14),  @Son_Kalan_Tutar float,  @IslemTuru nvarchar(20), @TmpTutar decimal(28, 14)      
    
declare cr_Rut cursor FAST_FORWARD READ_ONLY for      
select  CariNo from [VRUT] where @RutAdi is not null and RutAdi =@RutAdi and Deger = @RutGunu and SaticiAdi = @RutSatici   
union ALL   
select MUSNO from AMUSTERI where MUSBAKIYE > 0.01 and  @RutAdi is null  
open cr_Rut      
fetch next from cr_Rut      
into  @CariNo    
while (@@FETCH_STATUS = 0)    
begin    
    
 set @DagitimTutari = (select SUM (BORC-ALACAK) from ACARI WHERE MUSNO=@CariNo)       
 set @TmpTutar = @DagitimTutari      
      
 declare cr_Prepare cursor FAST_FORWARD READ_ONLY for      
 select         
   odm.NoId,      
   odm.IslemNo,      
   odm.Tarih,      
   odm.CariNo,      
   odm.Borc,      
   odm.BAAcikla      
 from Odeme odm      
 where      
    odm.CariNo = @CariNo and      
    IsNull (odm.Borc, 0) > 0      
 order by      
   odm.Tarih desc,NoId desc      
      
 open cr_Prepare      
 fetch next from cr_Prepare      
 into      
   @NoId,      
   @IslemNo,      
   @Tarih,      
   @CariNo,      
   @Borc,      
   @IslemTuru      
      
 while (@@FETCH_STATUS = 0) and (@TmpTutar > 0.0)      
 begin      
   if @Borc >= @TmpTutar       
   begin      
  set @Borc_Kullanilan = @TmpTutar      
  set @Son_Kalan_Tutar = @TmpTutar - @Borc      
  set @TmpTutar = 0.0      
   end      
   else      
   begin      
  set @TmpTutar = @TmpTutar - @Borc      
  set @Borc_Kullanilan = @Borc      
  set @Son_Kalan_Tutar = @TmpTutar      
   end      
      
   insert into #odeme       
   (      
  NoId,      
  IslemNo,      
  Tarih,      
  CariNo,      
  Borc,      
  Borc_Kullanilan,      
  Devreden,      
  Bakiye,      
  Devir,      
  IslemTuru      
   )      
   values      
   (      
  @NoId,       
  @IslemNo,      
  @Tarih,      
  @CariNo,      
  @Borc,      
  @Borc_Kullanilan,      
  @Son_Kalan_Tutar,      
  @DagitimTutari,      
  @Son_Kalan_Tutar+@Borc,      
  @IslemTuru      
   )      
      
   fetch next from cr_Prepare      
   into      
  @NoId,      
  @IslemNo,      
  @Tarih,      
  @CariNo,      
  @Borc,      
  @IslemTuru      
 end      
        
 close cr_Prepare      
 deallocate cr_Prepare       
    
   FETCH NEXT FROM cr_Rut  INTO @CariNo    
end       
close cr_Rut      
deallocate cr_Rut         
    
select      
  RecID,    
  o.NoId,    
  a.MUSNO  [Cari No],      
  a.MUSKOD [Cari Kodu],      
  a.MUSADI [Cari Adı],      
  o.IslemTuru [İşlem Türü],      
  o.IslemNo [İşlem No],      
  c.ACIKLAMA [Açıklama],      
  CONVERT(nvarchar(10),c.TARIH,104)  [İşlem Tarihi],      
  CONVERT(nvarchar(10),o.Tarih,104)  [Vade Tarihi],      
  CAST(GETDATE() - o.Tarih as int) [Geciken Gün],      
  Devreden,    
  o.Borc [Borç],      
  o.Devir,      
  o.Bakiye,      
  d.FatSerNo [Fatura Seri No],      
  d.FaturaNo [Fatura No]      
 from #odeme o      
 inner join  AMUSTERI a on  o.CariNo = a.MUSNO      
 inner join  ACARI    c on c.ISLEMNO = o.IslemNo and c.MUSNO = o.CariNo and c.BAACIKLA = o.IslemTuru     
 left join   STOKHARDETBAG d on o.IslemNo = d.IslemNo      
 Order by a.MUSNO,o.Tarih desc, o.NoId desc 
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if exists (select * from sys.procedures where name='spTahsilVadeRaporu')
drop proc spTahsilVadeRaporu
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
create   proc spTahsilVadeRaporu @CariNo int       
as      
create table #odeme      
(      
  RecID integer Identity (1, 1) not null, NoId integer, IslemNo integer, Tarih datetime,      
  CariNo integer,  IslemTuru nvarchar(20) COLLATE DATABASE_DEFAULT,  Bakiye float,  Borc_Kullanilan float ,  Devreden float,  Borc float,      
  Devir float  PRIMARY KEY CLUSTERED  (RecID)      
)      
      
      
Declare @DagitimTutari float      
set @DagitimTutari = (select SUM (BORC-ALACAK) from ACARI WHERE MUSNO=@CariNo)      
      
Declare  @NoId integer,  @IslemNo integer,  @Tarih datetime,  @Borc decimal (28, 14),        
   @Borc_Kullanilan decimal (28, 14),  @Son_Kalan_Tutar float,  @IslemTuru nvarchar(20), @TmpTutar decimal(28, 14)      
      
set @TmpTutar = @DagitimTutari      
      
declare cr_Prepare cursor FAST_FORWARD READ_ONLY for      
select         
  odm.NoId,      
  odm.IslemNo,      
  odm.Tarih,      
  odm.CariNo,      
  odm.Borc,      
  odm.BAAcikla      
from Odeme odm      
where      
   odm.CariNo = @CariNo and      
   IsNull (odm.Borc, 0) > 0      
order by      
  odm.Tarih desc,NoId desc      
      
open cr_Prepare      
fetch next from cr_Prepare      
into      
  @NoId,      
  @IslemNo,      
  @Tarih,      
  @CariNo,      
  @Borc,      
  @IslemTuru      
      
while (@@FETCH_STATUS = 0) and (@TmpTutar > 0.0)      
begin      
  if @Borc >= @TmpTutar       
  begin      
    set @Borc_Kullanilan = @TmpTutar      
 set @Son_Kalan_Tutar = @TmpTutar - @Borc      
 set @TmpTutar = 0.0      
  end      
  else      
  begin      
    set @TmpTutar = @TmpTutar - @Borc      
 set @Borc_Kullanilan = @Borc      
 set @Son_Kalan_Tutar = @TmpTutar      
  end      
      
  insert into #odeme       
  (      
    NoId,      
    IslemNo,      
    Tarih,      
    CariNo,      
    Borc,      
 Borc_Kullanilan,      
 Devreden,      
 Bakiye,      
 Devir,      
 IslemTuru      
  )      
  values      
  (      
 @NoId,       
 @IslemNo,      
    @Tarih,      
    @CariNo,      
    @Borc,      
 @Borc_Kullanilan,      
 @Son_Kalan_Tutar,      
 @DagitimTutari,      
 @Son_Kalan_Tutar+@Borc,      
 @IslemTuru      
  )      
      
  fetch next from cr_Prepare      
  into      
    @NoId,      
    @IslemNo,      
    @Tarih,      
    @CariNo,      
    @Borc,      
 @IslemTuru      
end      
        
close cr_Prepare      
deallocate cr_Prepare      
      
       
--  spTahsilVadeRaporu 42      
update AMUSTERI SET Kilitli='Kilitli' WHERE MUSNO IN (      
select  distinct o.CariNo  from #odeme o      
where o.Devir > (select Deger from Parametre  where Param = 'Vadesi Geçen Toplam')      
      and CAST(GETDATE() - o.Tarih as int) > (select Deger from Parametre  where Param = 'Vadesi Geçen Kilitlenecek Gün')       
 ) AND Kilitli='Açık'      
       
 update AMUSTERI SET  Kilitli='Açık' WHERE MUSNO NOT IN (      
select  distinct o.CariNo  from #odeme o      
where o.Devir > (select Deger from Parametre  where Param = 'Vadesi Geçen Toplam')      
      and CAST(GETDATE() - o.Tarih as int) > (select Deger from Parametre  where Param = 'Vadesi Geçen Kilitlenecek Gün')       
) AND Kilitli='Kilitli'      
      
select      
  a.MUSNO  [Cari No],      
  a.MUSKOD [Cari Kodu],      
  a.MUSADI [Cari Adı],      
  o.IslemTuru [İşlem Türü],      
  o.IslemNo [İşlem No],      
  c.ACIKLAMA [Açıklama],      
  c.TARIH  [İşlem Tarihi],      
  o.Tarih [Vade Tarihi],      
  CAST(GETDATE() - o.Tarih as int) [Geciken Gün],      
  o.Devir,      
  o.Borc [Borç],      
  o.Bakiye,      
  d.FatSerNo [Fatura Seri No],      
  d.FaturaNo [Fatura No]      
 from #odeme o      
 inner join  AMUSTERI a on  o.CariNo = a.MUSNO      
 inner join  ACARI    c on c.ISLEMNO = o.IslemNo and  c.MUSNO = o.CariNo and c.BAACIKLA = o.IslemTuru     
 left join   STOKHARDETBAG d on o.IslemNo = d.IslemNo      
 Order by o.Tarih desc, o.NoId desc   
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if exists (select * from sys.views where name='VStk_RenkBedenGirisCikisDepo')
drop VIEW VStk_RenkBedenGirisCikisDepo
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE VIEW VStk_RenkBedenGirisCikisDepo   
AS  
SELECT StokKodu,  
  Beden,  
  Renk,  
        (SELECT ISNULL(SUM(Miktar), 0) AS Expr1 FROM dbo.RenkBedenHareket   
        WHERE (StokKodu = AnaTablo.StokKodu) AND   
     (GC = 'G') AND   
     (Beden = AnaTablo.Beden) and   
     (Renk = AnaTablo.Renk) AND   
     (Depo = AnaTablo.Depo) and  
     (HT = AnaTablo.HT)) AS Giris,  
  (SELECT ISNULL(SUM(Miktar), 0) AS Expr1 FROM dbo.RenkBedenHareket  
   WHERE (StokKodu = AnaTablo.StokKodu) AND   
      (GC = 'C') AND   
      (Beden = AnaTablo.Beden) and   
     (Renk = AnaTablo.Renk) AND   
     (Depo = AnaTablo.Depo) and  
     (HT = AnaTablo.HT)) AS Cikis,  
  (SELECT ISNULL(SUM(Miktar), 0) AS Expr1 FROM dbo.RenkBedenHareket   
        WHERE (StokKodu = AnaTablo.StokKodu) AND   
     (GC = 'G') AND   
     (Beden = AnaTablo.Beden) and   
     (Renk = AnaTablo.Renk) AND   
     (Depo = AnaTablo.Depo)and  
     (HT = AnaTablo.HT))-  
  (SELECT ISNULL(SUM(Miktar), 0) AS Expr1 FROM dbo.RenkBedenHareket  
   WHERE (StokKodu = AnaTablo.StokKodu) AND   
      (GC = 'C') AND   
      (Beden = AnaTablo.Beden) and   
     (Renk = AnaTablo.Renk) AND   
     (Depo = AnaTablo.Depo) and  
     (HT = AnaTablo.HT)) AS Fark,  
     Depo, HT,
	 (select rb.Barkodu from RenkBedenTablosu rb where rb.StokKodu = AnaTablo.StokKodu and rb.Beden = AnaTablo.Beden and rb.Renk = AnaTablo.Renk) Barkodu
FROM         dbo.RenkBedenHareket AS AnaTablo  
group by StokKodu,Beden,Renk,Depo,HT
go--
 
 IF NOT EXISTS (SELECT * FROM sys.indexes WHERE Name='uidx_IsoBirim_01')
BEGIN
CREATE UNIQUE INDEX uidx_IsoBirim_01 ON [ISOBIRIM] ([IsoBirimKodu],[IsoBirimAdi]);
END
go--

             				  
if  not  exists (select * from dbo.syscolumns where id = object_id(N'AnaMenuAyar') and name=N'AnaMenu')
begin
	ALTER TABLE AnaMenuAyar ADD AnaMenu BIT
end ELSE BEGIN
	ALTER TABLE AnaMenuAyar ALTER COLUMN AnaMenu BIT
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if not exists (SELECT 1 FROM VTGuncellemeleri WHERE VTVersiyon='7.1.1')
BEGIN
insert into VTGuncellemeleri (VTVersiyon, SonIslemNo, TarihSaat, Prg)
VALUES ('7.1.1',(select ISLEMNO from ADIGSABITLER ),GETDATE(),'OM')
END

go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if  not  exists (select * from dbo.syscolumns where id = object_id(N'AcariTakas') and name=N'DovizKur')
begin
	ALTER TABLE AcariTakas ADD DovizKur float
end ELSE BEGIN
	ALTER TABLE AcariTakas ALTER COLUMN DovizKur float
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if  not  exists (select * from dbo.syscolumns where id = object_id(N'AnaMenuAyar') and name=N'Kart')
begin
	ALTER TABLE AnaMenuAyar ADD Kart BIT
end ELSE BEGIN
	ALTER TABLE AnaMenuAyar alter column Kart BIT
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if  not  exists (select * from dbo.syscolumns where id = object_id(N'AnaMenuAyar') and name=N'Rapor')
begin
	ALTER TABLE AnaMenuAyar ADD Rapor BIT
end ELSE BEGIN
	ALTER TABLE AnaMenuAyar alter column Rapor BIT
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if  not  exists (select * from dbo.syscolumns where id = object_id(N'AnaMenuAyar') and name=N'IslemGiris')
begin
	ALTER TABLE AnaMenuAyar ADD IslemGiris BIT 
end ELSE BEGIN
	ALTER TABLE AnaMenuAyar ALTER COLUMN IslemGiris BIT 
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
delete GridView where KayitIsmi in ('FrmStokIslemlericxGrid1cxGrid1DBTableView1',
 				'FrmFaturaIslemlericxGrid1cxGrid1DBTableView1',
 				'frmCaricxCariHareketlertvACARI',
 				'FrmCariDetRapcxGrid1tvHareketler',
 				'FrmFCariDovizlicxGrid1tvACARI',
 				'FrmCariIslemlericxGrid1cxGrid1DBTableView1')
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if exists (select * from sys.procedures where name='spMalSayimiDuzenle')
drop proc spMalSayimiDuzenle
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
create  proc spMalSayimiDuzenle 
as
---Malsayım detbag kaydı olmayanları düzenler
declare @IslemNo int declare @GC nvarchar(1) declare @KullaniciAdi nvarchar(20) declare @ParamKullaniciNo int
declare @DovizKodu nvarchar(2) declare @DovizId smallint declare @Depo nvarchar(30) declare @KullaniciDepartmani nvarchar(8)
declare @Tutar money declare @KdvTutari money declare @DovizliTutar money declare @SevkTarihi datetime declare @DovizKuru money=1

declare @FaturaTarihi datetime 

declare StoklarCursor cursor            
for            
	Select IslemNo,SUM(Tutar) Tutar,SUM(KdvTutari)KdvTutari,SUM(DovizliTutar) DovizliTutar,SevkTarihi
	from (
		select	IslemNo,
				CASE WHEN GC = 'G' THEN SonTutar ELSE SonTutar * (-1) end Tutar, 
				CASE WHEN GC = 'G' THEN KdvTutari ELSE KdvTutari * (-1) end KdvTutari, 
				CASE WHEN GC = 'G' THEN DovizTut ELSE DovizTut * (-1) end DovizliTutar, 
			   SiparisTarihi as SevkTarihi  
		from STOKHAR where IslemTuru='Mal Sayımı' and not exists (select * from STOKHARDETBAG where IslemNo=STOKHAR.IslemNo and IslemTuru=STOKHAR.IslemTuru)  
	) tbl
	GROUP BY IslemNo,SevkTarihi

         
 open StoklarCursor            
 fetch next from StoklarCursor into @IslemNo,@Tutar,@KdvTutari,@DovizliTutar,@SevkTarihi           
            
while @@FETCH_STATUS =0             
begin

select top 1 @FaturaTarihi=FaturaTarihi,@KullaniciAdi=KULADI,@ParamKullaniciNo=KULNO,
@DovizKodu=DovizKodu,@DovizId=DovizCinsi,@Depo=Depo,@KullaniciDepartmani=Departman,@DovizKuru=DovizKuru from STOKHAR where IslemNo=@IslemNo and IslemTuru='Mal Sayımı' 


IF @Tutar >= 0
	SET @GC = 'G'
ELSE
	SET @GC = 'C';

exec spStokHarDetBagKaydet /*@IslemNo*/ @IslemNo, /*@IslemTuru*/ 'Mal Sayımı',/*:CariNo*/0,/*:CariKodu*/'Mal Sayımı',/*:CariAdi*/'Mal Sayımı',/*@Tutar*/ @Tutar,                       
   /*@SiparisTarihi*/ @FaturaTarihi,/*@KdvTutari*/ @KdvTutari, /*@FisTuru*/'M',/*:GC*/@GC,/*:EkIskTut1*/0 ,/*:EkIskTut2*/0 ,/*:EkIskTut3*/0 ,/*:EkIskTutTop*/0 ,                    
   /*:FaturaNo*/0,/*:FaturaTarihi*/ @FaturaTarihi, /*:Satici*/'',/*:DovizTut*/@DovizliTutar ,/*:DovizCinsi*/@DovizId ,/*:DovizKodu*/@DovizKodu ,/*  @DovizTutB*/@DovizliTutar,                    
   /*@BelgeNo*/'', /*@OzelKod1*/'',/*@OzelKod2*/'',/*@OzelKod3*/'',/*@IslemTipi*/'',/*@IrsNo*/'',/*@Ack1*/'',/*@Ack2*/'',/*@Ack3*/'',/*@Ack4*/'',/*:KULNO*/@ParamKullaniciNo ,
   /*:KULADI*/@KullaniciAdi ,                    
   /*@FatSerNo*/'',/*@SaticiAdi*/'',/*@AltIskYuzde1*/0,/*@AltIskYuzde2*/0,/*@AltIskYuzde3*/0,/*@AK*/'',/*@FaturaOPlanGunu*/0,/*@Depo*/@Depo,/*@GunAy*/0,/*@OpsiyonGunu*/0,                    
   /*@AcikKapali*/'A',/*@DovizBorc*/0,/*@DovizAlacak*/0,/*@FYaz*/'',/*@SecimEH*/'',/*@IslemNo3*/0,/*@TP*/'TF',/*@FisNo*/'',/*@VardiyaKodu*/'',/*@VardiyaDurumu*/'',/*@Departman*/@KullaniciDepartmani,                    
   /*@MasrafToplami*/0,/*@KDVDH*/'H',/*@IslemNo4*/0,/*@KayitDuzeyi*/0,/*@YazarKasaNo*/0,/*@YazarKasaFisNo*/'',/*@YaziciCount*/0,/*@IsIstasyonKodu*/'',/*@IsIstasyonAdi*/'',                    
   /*@TevkifatTutari*/0,/*@VardiyaNo*/'',/*@OdemeBilgisi*/'',/*@FaturaAdresNo*/ 0,/*@SevkAdresNo*/ 0,/*@FI*/ 'E',/*@SevkTarihi*/@SevkTarihi,/*@eFaturaNo*/'',                    
   /*@UUID*/ '',/*@eFaturaGonderimTarihi*/ null,/*@eFaturaDurumu*/'',/*@FaturaTipi*/0,@DovizKuru

  fetch next from StoklarCursor into @IslemNo,@Tutar,@KdvTutari,@DovizliTutar,@SevkTarihi              
end            
            
close StoklarCursor            
deallocate StoklarCursor 
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if  not  exists (select * from dbo.syscolumns where id = object_id(N'Tevkifat') and name=N'IslemNo2')
begin
	ALTER TABLE Tevkifat ADD IslemNo2 int
end ELSE BEGIN
	ALTER TABLE Tevkifat ALTER COLUMN IslemNo2 int
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
UPDATE t SET t.IslemNo2 = h.IslemNo2 from Tevkifat t,STOKHAR h where t.StokNo = h.StokNo and t.IslemNo in (h.IslemNo,h.IslemNo3) 
go-- 
		 
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if exists (select * from sys.procedures where name='sp_DepoSifirla')
drop proc sp_DepoSifirla
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
create   procedure sp_DepoSifirla(@ParamDepo varchar(250),@ParamGrupAdi varchar(250),@ParamKullaniciNo int,            
@ParamReferansFiyat varchar(100),@ParamTarih nvarchar(8),@BelgeNo varchar(20) = '',@BelgeAciklama varchar(100) = '' )            
as                     
create table #Stoklar(StokNo int ,Kodu varchar(50),StokKodu varchar(50),StokAdi varchar(500),GrupAdi varchar(500),UreticiFirmaKodu varchar(250),            
OzelKod1 varchar(250), OzelKod2 varchar(250), AnaBirim varchar(250),            
AktifPasif varchar(5), Giris float, Cikis float, StokAdedi float, Depo varchar(500),Fiyat money)            
            
declare @SiraNo int             
declare @KacKayitVar int            
declare @FaturaTarihi datetime            
declare @FaturaMiktari money declare @Miktar  money declare @BirimMiktar money declare @BirimFiyat money declare @NFiyat money             
declare @Tutar money declare @TopTutar money declare @DovizTutB money declare @DovizTut money declare @GenelToplamTutar money             
declare @DovizGunFiyati money             
declare @DovizliTutar money             
declare @NFiyatDovBr money            
            
declare @GC varchar(50) declare @DovizId varchar(50)              
declare @DovizKodu varchar(50)  declare @IslemNo  varchar(50)             
declare @KullaniciAdi varchar(250)            
declare @KullaniciVardiya varchar(250)            
declare @KullaniciVardiyaNo varchar(250)            
            
declare @KullaniciDepartmani varchar(50)            
declare @SqlText nvarchar(max)            
     
    
    
set @KullaniciVardiya='99';            
set @KullaniciVardiyaNo='20090101';            
            
select top 1 @KullaniciDepartmani=Departman,@KullaniciAdi=GirisAdi from Kullanicilar where No=@ParamKullaniciNo            
            
set @SqlText='UPDATE STOKKARTI ' +            
                       ' SET StokAdedi = (SELECT ISNULL(SUM(Miktar), 0) from STOKHAR ' +            
                       ' WHERE StokKodu = STOKKARTI.Kodu and GC=''G'' and FisTuru<>''İ'')-' +            
                       ' (SELECT ISNULL(SUM(Miktar), 0) from STOKHAR '+            
                       ' WHERE StokKodu = STOKKARTI.Kodu and GC=''C'' and FisTuru<>''İ'')';            
            
exec(@SqlText)            
            
 select top 1 @DovizKodu=Deger from KullaniciAyarlari where Ayar='VarsayilanDovizKodu'            
 select TOP 1 @DovizId=NoId,@DovizGunFiyati=GunFiyati from DOVIZT where DovizKodu=@DovizKodu            
             
  SELECT @IslemNo = ISLEMNO FROM ADIGSABITLER              
  Update ADIGSABITLER SET ISLEMNO=ISLEMNO+2              
  set @SiraNo = 1            
  set @GenelToplamTutar = 0            
    
  insert into #Stoklar            
   exec sp_DepoDurumlari @ParamTarih    
     
  delete from #Stoklar where @ParamDepo != Depo  
      
  if @ParamGrupAdi<>''    
  delete from #Stoklar where GrupAdi<>@ParamGrupAdi    
      
declare @StokNo int             
declare @Kodu varchar(50)            
declare @StokAdi varchar(500)            
declare @GrupAdi varchar(500)            
declare @UreticiFirmaKodu varchar(250)            
declare @OzelKod1 varchar(250)            
declare @OzelKod2 varchar(250)            
declare @AnaBirim varchar(250)            
declare @AktifPasif varchar(5)            
declare @Giris float            
declare @Cikis float            
declare @StokAdedi float            
declare @Depo varchar(500)            
declare @Fiyat money            
            
declare StoklarCursor cursor            
for            
 select StokNo,Kodu ,StokAdi ,GrupAdi ,UreticiFirmaKodu ,OzelKod1 , OzelKod2 , AnaBirim ,            
  AktifPasif , Giris , Cikis , StokAdedi , Depo,Fiyat  from #Stoklar            
 open StoklarCursor            
 fetch next from StoklarCursor into @StokNo,@Kodu,@StokAdi,@GrupAdi,@UreticiFirmaKodu,@OzelKod1,@OzelKod2,@AnaBirim,            
  @AktifPasif,@Giris,@Cikis,@StokAdedi,@Depo,@Fiyat            
            
while @@FETCH_STATUS =0             
begin            
            
set @Miktar = 0;            
            
    if @StokAdedi> 0 begin   
      set @FaturaMiktari = @StokAdedi;            
      set @Miktar    = @StokAdedi;            
      set @BirimMiktar   = 1;   
      set @BirimFiyat    = @Fiyat;            
      set @NFiyat        = @Fiyat;            
      set @Tutar         = @Fiyat * @StokAdedi;            
      set @TopTutar      = @Fiyat*@StokAdedi;            
      set @GC            = 'C';            
      set @DovizTutB     = @Fiyat/ @DovizGunFiyati;            
      set @DovizTut      = @StokAdedi* @DovizTutB;            
    end else            
    if @StokAdedi< 0 begin            
      set @FaturaMiktari = -(@StokAdedi);            
      set @Miktar        = -(@StokAdedi);            
      set @BirimMiktar   = 1;            
      set @BirimFiyat    = @Fiyat;            
      set @NFiyat        = @Fiyat;            
      set @Tutar         = @Fiyat * (-@StokAdedi);            
      set @TopTutar      = @Fiyat * (-@StokAdedi);            
      set @GC            = 'G';            
      set @DovizTutB     = @Fiyat / @DovizGunFiyati;            
      set @DovizTut      = (-(@StokAdedi))* @DovizTutB;            
    end;            
  set @GenelToplamTutar = @GenelToplamTutar + @TopTutar;            
set @FaturaTarihi=convert(datetime,@ParamTarih);  
set @DovizliTutar=@TopTutar/@DovizGunFiyati            
set @NFiyatDovBr=@Fiyat/@DovizGunFiyati            
  
 exec spStokHarKaydet  @IslemNo,'Mal Sayımı',0,'Mal Sayımı','Mal Sayımı',            
   @StokNo ,@Kodu ,@StokAdi,@Miktar,@AnaBirim,@BirimMiktar,        
   @BirimFiyat,0,0,0,0,@Tutar,@SiraNo,    @FaturaTarihi,0,0,0 ,0 ,'M',            
   @GC ,0 ,0 ,0 ,0 ,0 , @FaturaTarihi,               
   '' ,@TopTutar ,'H' ,@DovizliTutar ,@DovizId ,@DovizKodu ,            
            
   @DovizTutB ,@Depo ,@Fiyat ,@FaturaMiktari ,0 ,            
   0 ,0 ,@ParamKullaniciNo ,@KullaniciAdi ,'' ,0 ,            
   0 ,0 ,'A' ,0 ,0 ,            
               
   0 ,0 ,'' ,'' ,'' ,'' ,            
   'TF' ,@KullaniciVardiya ,'H' ,0 ,@KullaniciDepartmani ,@TopTutar ,            
   @DovizliTutar ,0 ,0 ,0 ,0 ,            
        
   0 ,@AnaBirim ,0 ,@Fiyat ,0 ,            
   0 ,0 ,@Fiyat ,@NFiyatDovBr ,'+ Ürün' ,@KullaniciVardiya ,            
   'Genel' ,@SiraNo ,0 ,0 ,0 ,0 , 0,            
            
   0 ,0,0 ,0 ,0 ,0 ,            
   0 ,0 ,0 ,'' ,'' , 0,            
   'YOK' , 'YOK','YOK' ,@FaturaMiktari ,0,0            
set @SiraNo = @SiraNo + 1;            
 fetch next from StoklarCursor into @StokNo,@Kodu,@StokAdi,@GrupAdi,@UreticiFirmaKodu,@OzelKod1,@OzelKod2,@AnaBirim,            
  @AktifPasif,@Giris,@Cikis,@StokAdedi,@Depo,@Fiyat            
end    
            
close StoklarCursor            
deallocate StoklarCursor    
EXEC spMalSayimiDuzenle
delete from STOKHAR where Miktar=0
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if exists (select * from sys.procedures where name='sp_StokFiyatDegistir')
drop proc sp_StokFiyatDegistir
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
create    proc sp_StokFiyatDegistir(@ParamSeciliStokKodlari nvarchar(max),@ParamDegisecekFiyatIndex int=0,@ParamReferansAlanAdi nvarchar(50),              
@ParamIslemTur1 varchar(1)='',@ParamIslemDeger1 nvarchar(50)='1',@ParamIslemTur2 varchar(1)='',@ParamIslemDeger2 nvarchar(50)='1',@HaneSayisi nvarchar(10) = '8')              
as                           
  declare @i integer               
  declare @Sqlexec nvarchar(max)              
  declare @IslemDeger1 float              
  declare @IslemDeger2 float              
  declare @IslemDeger3 float              
              
  set @IslemDeger1=CONVERT(float,@ParamIslemDeger1)              
  set @IslemDeger2=CONVERT(float,@ParamIslemDeger2)                     
                
  declare @HesapSql nvarchar(max)              
  set @HesapSql=''              
              
  if @ParamDegisecekFiyatIndex>0              
  begin         
    -- Toplu fiyat güncelleme ekranında sayısal değer girilidğinde yapılacak işlem      
 declare @sonuc int = 0,@Deger float;      
 BEGIN TRY        
	SET @Deger =  CAST( REPLACE(@ParamReferansAlanAdi,',','.') as float) 
	SET @sonuc = 0;      
 END TRY        
 BEGIN CATCH        
	SET @sonuc = 1;      
 END CATCH        
   --      
   IF @sonuc = 0       
   BEGIN      
		SET @HesapSql=	' update StokFiyat SET F'+convert(varchar,@ParamDegisecekFiyatIndex)+'Fiyat= (case F'+convert(varchar,@ParamDegisecekFiyatIndex)+'Kdv when ''D'' then  '+REPLACE(@ParamReferansAlanAdi,',','.')+' '+                
 	' when ''H'' then  ('+REPLACE(@ParamReferansAlanAdi,',','.')+'/(100 + SatisKdv)) * 100 end )  where StokNo in ( '+@ParamSeciliStokKodlari+')  ';            
    
 --SET @HesapSql=' update StokFiyat SET F'+convert(varchar,@ParamDegisecekFiyatIndex)+'FiyatH='+REPLACE(@ParamReferansAlanAdi,',','.')+' where StokNo in ( '+@ParamSeciliStokKodlari+')';         
   END      
   ELSE      
   IF CHARINDEX('Fiyat',@ParamReferansAlanAdi) > 0           
   BEGIN      
		set @HesapSql=' update StokFiyat SET F'+convert(varchar,@ParamDegisecekFiyatIndex)+'Fiyat=ROUND(((SF.'+@ParamReferansAlanAdi;              
              
		if( @ParamIslemTur1!='' and @ParamIslemDeger1!='')              
			set @HesapSql=@HesapSql+@ParamIslemTur1+@ParamIslemDeger1+')'    
		else     
			set @HesapSql =  @HesapSql + ')';    
              
		if( @ParamIslemTur2!='' and @ParamIslemDeger2!='')              
			set @HesapSql=@HesapSql+@ParamIslemTur2+@ParamIslemDeger2;      
       
		if @HesapSql!=''              
			set @HesapSql=@HesapSql+'),'+@HaneSayisi+')  from StokFiyat as SF where StokNo in ( '+@ParamSeciliStokKodlari+')';              
   END          
   ELSE          
   BEGIN         
		IF @ParamReferansAlanAdi = 'Fifo'
			SET @ParamReferansAlanAdi = 'FifoFiyat'

		IF @ParamReferansAlanAdi = 'Lifo'
			SET @ParamReferansAlanAdi = 'LifoFiyat'

			set @HesapSql=' update SF SET F'+convert(varchar,@ParamDegisecekFiyatIndex)+'Fiyat=ROUND(((SF2.'+@ParamReferansAlanAdi;              
              
		if( @ParamIslemTur1!='' and @ParamIslemDeger1!='')              
			set @HesapSql=@HesapSql+@ParamIslemTur1+@ParamIslemDeger1+')'    
		else 
			set @HesapSql =  @HesapSql + ')';      
              
		if( @ParamIslemTur2!='' and @ParamIslemDeger2!='')              
			set @HesapSql=@HesapSql+@ParamIslemTur2+@ParamIslemDeger2;               
              
		if @HesapSql!=''              
			set @HesapSql=@HesapSql+'),'+@HaneSayisi+')   from StokFiyat as SF,StokFiyatlari SF2 where SF.StokNo = SF2.StokNo and  SF.StokNo in ( '+@ParamSeciliStokKodlari+')';             
   END;          
          
   set @Sqlexec=@HesapSql+CHAR(13)+CHAR(10)+' update StokFiyat SET F'+convert(varchar,@ParamDegisecekFiyatIndex)+'FiyatH  = '+     
                             ' (case F'+convert(varchar,@ParamDegisecekFiyatIndex)+'Kdv when ''H'' then  F'+convert(varchar,@ParamDegisecekFiyatIndex)+'Fiyat '+                
           ' when ''D'' then  (F'+convert(varchar,@ParamDegisecekFiyatIndex)+'Fiyat/(100 + SatisKdv)) * 100 end )  where StokNo in ( '+@ParamSeciliStokKodlari+')  ';            
             
  end               
 --  print(@Sqlexec)             
            
  set @Sqlexec=@Sqlexec+CHAR(13)+CHAR(10)+ ' update s                 
   set s.F1Fiyat = f.F1Fiyat,s.F1Kdv = f.F1Kdv,s.F1DovizKodu = f.F1DovizKodu,                
     s.F2Fiyat = f.F2Fiyat,s.F2Kdv = f.F2Kdv,s.F2DovizKodu = f.F2DovizKodu,              
     s.F3Fiyat = f.F3Fiyat,s.F3Kdv = f.F3Kdv,s.F3DovizKodu = f.F3DovizKodu,                
     s.F4Fiyat = f.F4Fiyat,s.F4Kdv = f.F4Kdv,s.F4DovizKodu = f.F4DovizKodu                
 from  STOKKARTI s,StokFiyat f                 
where  s.Kodu = f.Kodu                 
  and  s.StokNo in ( '+@ParamSeciliStokKodlari+') ';            
            
-- print(@Sqlexec)            
-- select @Sqlexec              
 exec(@Sqlexec)   
 go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 if exists (select * from sys.procedures where name='sp_StokIslemleriListesi')
drop proc sp_StokIslemleriListesi
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE    PROCEDURE [dbo].[sp_StokIslemleriListesi]             
 @tarih1 varchar(20),             
 @tarih2 varchar(20),             
 @dep varchar(500),             
 @orderby int,             
 @arama varchar(100),             
 @GosterilecekKayit int,             
 @IslemTuru varchar(20),             
 @Durumu int,             
 @IslemTipi varchar(30),      
 @IslemNoLike bit = 0  ,    
 @FatSerNo  varchar(3),                    
 @eFaturaNo  varchar(30)    
 --with encryption             
AS            
declare @str varchar(max)            
declare @rc int             
declare @tmp table (trc int)         
declare @ayrac varchar(2)                    
declare @peFaturaNo varchar(50)            
if @eFaturaNo<>''            
select @peFaturaNo=UPPER(@eFaturaNo)            
else set @peFaturaNo=''            
set @ayrac='"';     
             
set @str='select count(*) from (select IslemNo from STOKHARDETBAG where FI = ''E'' and TP=''TF'' AND FaturaTarihi >='''+ @Tarih1+''' and FaturaTarihi <= '''+@Tarih2+'''';             
    
if @peFaturaNo<>''                    
set @str=@str+'and (upper(eFaturaNo) like upper(''%'+@peFaturaNo+'%'') OR upper(EIrsaliyeNo) like upper(''%'+@peFaturaNo+'%'')) '       
    
if @FatSerNo<>''                    
set @str=@str+'and Replace(FatSerNo,'''''''','''+@ayrac+''') = '''+@FatSerNo+''' '      
    
if @dep <> ''             
 set @str=@str+' and Departman in ('+@Dep+')'             
if @IslemTuru <> 'Tümü'             
 set @str=@str+' and IslemTuru = '''+@IslemTuru+''''             
if @IslemTipi <> 'Tümü' and @IslemTipi <> ''             
 set @str=@str+' and IslemTipi like ''%'+@IslemTipi+'%'''                      
        
if @Durumu = 1                                
 set @str=@str+' and IslemTuru in (''Alış'',''Alış İade'',''Satış'',''Satış İade'') and FisTuru = ''I''  and AcikKapali=''A'' ' --Açıklar   /* and not exists (select IslemNo from STOKHAR where STOKHAR.IslemNo3=STOKHARDETBAG.IslemNo)*/                      
             
if @Durumu = 2                                
 set @str=@str+' and not(IslemTuru in (''Alış'',''Alış İade'',''Satış'',''Satış İade'') and FisTuru = ''I''  and AcikKapali=''A'') ' --Kapalılar                                
if @Durumu = 3                                
 set @str=@str+' and FisTuru > ''2''' --Stokİşlemi değilse                
            
if @arama <> ''       
begin            
if @orderby=0       
begin      
  if @IslemNoLike = 0      
  set @str=@str+'and CAST(IslemNo as nvarchar(20)) = '''+@arama+''' '       
  else      
  set @str=@str+'and IslemNo like ''%'+@arama+'%'' '       
 end;      
      
 if @orderby=1             
  set @str=@str+'and upper(CariAdi) like upper(''%'+@arama+'%'') '             
 if @orderby=2             
  set @str=@str+'and upper(FaturaNo) like upper('''+@arama+'%'') '             
 if @orderby=3             
  set @str=@str+'and upper(SiparisTarihi) like upper(''%'+@arama+'%'') '             
 if @orderby=4             
  set @str=@str+'and (upper(IrsNo) like upper('''+@arama+'%'')  or upper(EIrsaliyeNo) like upper('''+@arama+'%''))'             
 if @orderby=5             
  set @str=@str+'and upper(IslemNo) like upper('''+@arama+'%'') '             
end;             
set @str=@str+')Y';             
     
insert @tmp exec(@str)             
select @rc = trc from @tmp;             
             
declare @tstr varchar(1000);             
             
if @orderby=0             
 set @tstr='IslemNo'             
if @orderby=1             
 set @tstr='CariAdi'             
if @orderby=2             
 set @tstr='FaturaNo'             
if @orderby=3             
 set @tstr='SiparisTarihi'             
if @orderby=4             
 set @tstr='IrsNo'             
if @orderby=5             
 set @tstr='IslemNo'             
             
set @str='select * from STOKHARDETBAG '+             
 'where IslemNo in (select X.IslemNo '+             
 'from (select ROW_NUMBER() over (order by '+@tstr+') as sira, IslemNo '+             
 'from STOKHARDETBAG where FI = ''E'' and TP=''TF'' and FaturaTarihi >='''+@Tarih1+''' and FaturaTarihi <= '''+@Tarih2+'''';             
    
if @peFaturaNo<>''                    
set @str=@str+'and (upper(eFaturaNo) like upper(''%'+@peFaturaNo+'%'') OR upper(EIrsaliyeNo) like upper(''%'+@peFaturaNo+'%''))'       
    
if @FatSerNo<>''                    
set @str=@str+'and Replace(FatSerNo,'''''''','''+@ayrac+''') = '''+@FatSerNo+''' '      
    
if @dep <> ''             
 set @str=@str+' and Departman in ('+@Dep+')'             
if @IslemTuru <> 'Tümü'             
 set @str=@str+' and IslemTuru = '''+@IslemTuru+''''             
if @IslemTipi <> 'Tümü' and @IslemTipi <> ''             
 set @str=@str+' and IslemTipi = '''+@IslemTipi+''''             
            
if @Durumu = 1                                
 set @str=@str+' and IslemTuru in (''Alış'',''Alış İade'',''Satış'',''Satış İade'') and FisTuru = ''I''  and AcikKapali=''A'' ' --Açıklar     /* and not exists (select IslemNo from STOKHAR where STOKHAR.IslemNo3=STOKHARDETBAG.IslemNo)*/                   
  
if @Durumu = 2                                
 set @str=@str+' and not(IslemTuru in (''Alış'',''Alış İade'',''Satış'',''Satış İade'') and FisTuru = ''I'' and AcikKapali=''A'') ' --Kapalılar                                
if @Durumu = 3                                
 set @str=@str+' and FisTuru > ''2''' --Stokİşlemi değilse               
            
if @arama <> ''       
begin      
 if @orderby=0       
 begin      
  if @IslemNoLike = 0      
  set @str=@str+'and CAST(IslemNo as nvarchar(20)) = '''+@arama+''' '       
  else      
  set @str=@str+'and IslemNo like ''%'+@arama+'%'' '       
 end;         
 if @orderby=1             
  set @str=@str+'and upper(CariAdi) like upper(''%'+@arama+'%'') '             
 if @orderby=2             
  set @str=@str+'and upper(FaturaNo) like upper('''+@arama+'%'') '             
 if @orderby=3        set @str=@str+'and upper(SiparisTarihi) like upper(''%'+@arama+'%'') '             
 if @orderby=4             
  set @str=@str+'and (upper(IrsNo) like upper('''+@arama+'%'')  or upper(EIrsaliyeNo) like upper('''+@arama+'%''))'             
 if @orderby=5             
  set @str=@str+'and upper(IslemNo) like upper('''+@arama+'%'') '             
end;             
set @str=@str+')X where X.sira >'+convert(varchar,@rc - @GosterilecekKayit) +') order by ';             
             
if @orderby=0             
 set @str=@str+'IslemNo'             
if @orderby=1             
 set @str=@str+'CariAdi'             
if @orderby=2             
 set @str=@str+'FaturaNo'             
if @orderby=3             
 set @str=@str+'SiparisTarihi'             
if @orderby=4             
 set @str=@str+'IrsNo'             
if @orderby=5             
 set @str=@str+'IslemNo'             
       
--select @str as strislemsql           
exec(@str)   
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 if exists (select * from sys.procedures where name='sp_CARIEKSTRE')
drop proc sp_CARIEKSTRE
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE  PROCEDURE [dbo].[sp_CARIEKSTRE]                 
@MUSNO nvarchar(30), @ILKTARIH nvarchar(10),@SONTARIH nvarchar(10),                     
 @KAPALIHAREKET nvarchar(1),@ORTVADESEC nvarchar(1),@ISLEMTIPINEGORE SMALLINT=0,@ISLEMTIPINEGOREBAKIYEGRUPLA SMALLINT=0                 
 as    
 --  2024-05-18  ACIKLAMA 400 OLDU
BEGIN          
          
declare @pIslemTipi nvarchar(250)          
declare @pBAKIYE1 money          
           
           
DECLARE @ACARI TABLE (ROWNUMBER INT,TARIH DATETIME, TESSIRNO INT, MUSNO INT, BAACIKLA nvarchar(14),ACIKLAMA nvarchar(400),                    
  ISLEMNO INT,DOVIZTUT float,DOVIZKODU nvarchar(2),OZELKOD nvarchar(3),ISLEMTIPI nvarchar(30),                    
  BELGENO nvarchar(10), ACIKLABAKIYE nvarchar(1), TP nvarchar(2), [Ort Vade] DATETIME,SaticiKodu nvarchar(15),                    
  SaticiAdi nvarchar(25), KULNO INT,KULADI nvarchar(20), DovizBorc float,                    
  DovizAlacak float,Aciklama2 nvarchar(200),                    
  SiraNo INT, CARINO INT, MUSKOD nvarchar(20),MUSADI nvarchar(50), IsIstasyonKodu nvarchar(30),                     
  IsIstasyonAdi nvarchar(30), TESLIM nvarchar(200),BORC money, ALACAK money,  FARK money,                     
  BAKIYE money,eFaturaNo varchar(30),eFaturaDurumu varchar(20),eFaturaGonderimTarihi datetime,OdemeBilgisi nvarchar(100),DovizKur float)                    
DECLARE @BAKIYE money, @IBKY MONEY,@BAKIYE2 money                    
SELECT  @IBKY= SUM(BORC-ALACAK)  FROM ACARI WHERE MUSNO=@MUSNO AND TARIH<=@ILKTARIH                    
SET @BAKIYE = 0                    
IF @IBKY IS NULL                    
     SET @IBKY=0            
            
IF @ISLEMTIPINEGORE=1          
BEGIN          
  INSERT INTO @ACARI (ROWNUMBER,TARIH,MUSNO,FARK,BAKIYE,BAACIKLA,ACIKLAMA,ISLEMNO) VALUES (0,@ILKTARIH,@MUSNO,@IBKY,0,'Devir','Hesap Ekstresi Devir Tutarı',1);          
          
INSERT INTO @ACARI          
SELECT ROW_NUMBER() OVER(ORDER BY ISLEMTIPI ASC,TARIH ASC,CARINO ASC) AS ROWNUMBER1,TARIH,TESSIRNO,MUSNO,BAACIKLA,  
(ISNULL(ACIKLAMA, '''')+ ' - - ' +ISNULL((select TOP 1 STDB.Ack1 FROM STOKHARDETBAG as STDB where STDB.IslemNo=ACARI.ISLEMNO),'')) as ACIKLAMA,          
  
 ISLEMNO,DOVIZTUT,DOVIZKODU,OZELKOD,ISLEMTIPI,           
  ISNULL(BELGENO, '''') as [BELGENO],ACIKLABAKIYE,TP,VadeTarihi as Ort_Vade,SaticiKodu,          
  SaticiAdi, KULNO, KULADI, DovizBorc,           
  DovizAlacak,Aciklama2,          
  SiraNo, CARINO, MUSKOD, MUSADI, IsIstasyonKodu,           
  IsIstasyonAdi,(select TeslimEden + ' - - ' + TeslimAlan from ACIKLAMA where FATURANO = ISLEMNO) as Teslim,          
  BORC money, ALACAK money,(BORC-ALACAK), NULL,           
  (select top 1 A.eFaturaNo  from STOKHARDETBAG as A where A.IslemNo=ACARI.ISLEMNO) eFaturaNo,               
 (select top 1 A.eFaturaDurumu  from STOKHARDETBAG as A where A.IslemNo=ACARI.ISLEMNO) eFaturaDurumu,           
 (select top 1 A.eFaturaGonderimTarihi from STOKHARDETBAG as A where A.IslemNo=ACARI.ISLEMNO) eFaturaGonderimTarihi,        
 (select top 1 OdemeBilgisi from STOKHARDETBAG where IslemNo=ACARI.ISLEMNO ) as OdemeBilgisi,DovizKur         
 FROM ACARI           
 WHERE MUSNO=@MUSNO AND TARIH >@ILKTARIH AND TARIH<@SONTARIH           
 and 1=             
 case  when @KAPALIHAREKET is not null then  case  when AcikKapali <> @KAPALIHAREKET then 1 else 0 end else 1 end            
 ORDER BY ROWNUMBER1 ASC           
          
           
 END           
 ELSE       
 BEGIN          
INSERT INTO @ACARI (ROWNUMBER,TARIH,MUSNO,FARK,BAKIYE,BAACIKLA,ACIKLAMA,ISLEMNO) VALUES (0,@ILKTARIH,@MUSNO,@IBKY,0,'Devir','Hesap Ekstresi Devir Tutarı',1)          
 INSERT INTO @ACARI           
 SELECT ROW_NUMBER() OVER(ORDER BY  TARIH,CARINO  ,CARINO ASC) AS ROWNUMBER,TARIH,TESSIRNO,MUSNO,BAACIKLA,  
   
(ISNULL(ACIKLAMA, '''')+ ' - - ' +ISNULL((select TOP 1 STDB.Ack1 FROM STOKHARDETBAG as STDB where STDB.IslemNo=ACARI.ISLEMNO),'')) as ACIKLAMA,       
  
  ISLEMNO,DOVIZTUT,DOVIZKODU,OZELKOD,ISLEMTIPI,           
  ISNULL(BELGENO, '''') as [BELGENO],ACIKLABAKIYE,TP,VadeTarihi as [Ort Vade],SaticiKodu,          
  SaticiAdi, KULNO, KULADI, DovizBorc,           
  DovizAlacak,Aciklama2,          
  SiraNo, CARINO, MUSKOD, MUSADI, IsIstasyonKodu,           
  IsIstasyonAdi,(select TeslimEden + ' - - ' + TeslimAlan from ACIKLAMA where FATURANO = ISLEMNO) as Teslim,          
  BORC money, ALACAK money,(BORC-ALACAK), NULL,           
  (select top 1 A.eFaturaNo  from STOKHARDETBAG as A where A.IslemNo=ACARI.ISLEMNO) eFaturaNo,               
 (select top 1 A.eFaturaDurumu  from STOKHARDETBAG as A where A.IslemNo=ACARI.ISLEMNO) eFaturaDurumu,           
 (select top 1 A.eFaturaGonderimTarihi from STOKHARDETBAG as A where A.IslemNo=ACARI.ISLEMNO) eFaturaGonderimTarihi,        
 (select top 1 OdemeBilgisi from STOKHARDETBAG where IslemNo=ACARI.ISLEMNO ) as OdemeBilgisi,DovizKur        
 FROM ACARI           
 WHERE MUSNO=@MUSNO AND TARIH >@ILKTARIH AND TARIH<@SONTARIH           
 and 1=             
 case  when @KAPALIHAREKET is not null then  case  when AcikKapali <> @KAPALIHAREKET then 1 else 0 end else 1 end            
 ORDER BY ROWNUMBER ASC           
          
 END          
          
END            
      
declare @ROWNUMBER INT          
declare @IslemTipi1 varchar(250)          
          
declare AcariCursor cursor           
for Select ROWNUMBER,ISLEMTIPI FROM  @ACARI ORDER BY ROWNUMBER ASC           
FOR UPDATE OF BAKIYE OPEN AcariCursor          
FETCH NEXT FROM AcariCursor INTO @ROWNUMBER,@IslemTipi1          
WHILE @@FETCH_STATUS=0          
BEGIN           
          
IF @ISLEMTIPINEGORE=0           
BEGIN          
 SET @BAKIYE2=(SELECT SUM(ISNULL(FARK,0)) FROM @ACARI  WHERE ROWNUMBER<=@ROWNUMBER )          
 UPDATE TOP(1) @ACARI SET BAKIYE=@BAKIYE2 WHERE ROWNUMBER=@ROWNUMBER          
          
end  else          
begin          
          
if @ROWNUMBER=0          
 set @pIslemTipi=@IslemTipi1;          
          
   if @pIslemTipi=@IslemTipi1          
   begin          
    SET @BAKIYE2=(SELECT SUM(ISNULL(FARK,0)) FROM @ACARI  WHERE ROWNUMBER<=@ROWNUMBER and ISLEMTIPI=@pIslemTipi)          
    UPDATE TOP(1) @ACARI SET BAKIYE=@BAKIYE2 WHERE ROWNUMBER=@ROWNUMBER          
   end          
   else           
   begin          
    set @pIslemTipi=@IslemTipi1;          
    SET @BAKIYE2=(SELECT SUM(ISNULL(FARK,0)) FROM @ACARI  WHERE ROWNUMBER<=@ROWNUMBER and ISLEMTIPI=@pIslemTipi)          
    UPDATE TOP(1) @ACARI SET BAKIYE=@BAKIYE2 WHERE ROWNUMBER=@ROWNUMBER          
   end          
end          
          
 FETCH NEXT FROM AcariCursor INTO @ROWNUMBER,@IslemTipi1          
END          
CLOSE AcariCursor           
DEALLOCATE AcariCursor          
          
if @ISLEMTIPINEGOREBAKIYEGRUPLA=0          
SELECT  * FROM @ACARI  ORDER BY ROWNUMBER          
else          
SELECT  ISLEMTIPI,sum(BORC) as BORC,sum(ALACAK) as ALACAK,sum(BORC-ALACAK) as BAKIYE FROM @ACARI          
where ISLEMTIPI is not null and MUSNO=@MUSNO  GROUP BY ISLEMTIPI     
 go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 if exists (select * from sys.procedures where name='spStkDINAMIKInvoiceIhracatGtip')
drop proc spStkDINAMIKInvoiceIhracatGtip
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE    proc [dbo].[spStkDINAMIKInvoiceIhracatGtip] @Tarih1 datetime ,@Tarih2 datetime      as  
 select K.Kodu,K.StokAdi, H.Birim , H.Miktar , (H.BirimFiyat/H.DovizKuru) DovizBirimFiyatı,H.DovizKodu,(H.BirimFiyat/H.DovizKuru*H.Miktar)      TOPLAM ,
 H.DovizKodu,      H.IslemNo,H.IslemNo3,K.Aciklama2   , K.StokAdi2 ,K.UreticiFirmaKodu Uretici , K.GrupAdi   from STOKHAR H LEFT JOIN STOKKARTI K ON H.StokKodu=K.Kodu    
 where H.FaturaTarihi>=@Tarih1 and H.FaturaTarihi <=@Tarih2 
 go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if exists (select * from sys.procedures where name='spOdemeHareketSil')
drop proc spOdemeHareketSil
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE  PROCEDURE [dbo].[spOdemeHareketSil]   
   @IslemNo int,  
   @CariNo int,
   @BAAcikla nvarchar(50) = 'X'
AS  
	IF ISNULL(@BAAcikla,'X') = 'X'
		DELETE FROM Odeme WHERE (IslemNo = @IslemNo) and (CariNo = @CariNo)  
	ELSE
		DELETE FROM Odeme WHERE (IslemNo = @IslemNo) and (CariNo = @CariNo)  and BAAcikla = @BAAcikla;
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if not exists (SELECT 1 FROM VTGuncellemeleri WHERE VTVersiyon='7.1.2')
BEGIN
insert into VTGuncellemeleri (VTVersiyon, SonIslemNo, TarihSaat, Prg)
VALUES ('7.1.2',(select ISLEMNO from ADIGSABITLER ),GETDATE(),'OM')
END
go--

if exists (select * from sys.procedures where name='sp_StokHar_Masraf_Dagit')
drop proc sp_StokHar_Masraf_Dagit
go--
create  proc sp_StokHar_Masraf_Dagit(@IslemNo int,@Tip int,@MasrafTutar float)
as
begin
	if @Tip = 0 --Masraf tutarını fiyata göre dağıt
	begin
		update har SET har.SatMasrafTutari =  (@MasrafTutar*har.SonTutar) / (select Tutar from STOKHARDETBAG det where det.IslemNo in (har.IslemNo,har.IslemNo3)) from STOKHAR har where IslemNo = @IslemNo
	end;
	if @Tip = 1   --Masraf tutarını eşit dağıt
	begin
		update har SET har.SatMasrafTutari = @MasrafTutar /(select count(*) from STOKHAR where  IslemNo = @IslemNo or IslemNo3 = @IslemNo) from STOKHAR har where IslemNo = @IslemNo or IslemNo3 = @IslemNo
	end;

	UPDATE STOKHARDETBAG SET MasrafToplami = @MasrafTutar where IslemNo = @IslemNo;
end;
go--
if  not  exists (select * from dbo.syscolumns where id = object_id(N'GELGID') and name=N'DovizKuru')
begin
ALTER TABLE GELGID ADD DovizKuru Float
end
else begin
ALTER TABLE GELGID alter column DovizKuru float
end
go--
if exists (select * from sys.procedures where name='spGelirGiderYaz')
drop proc spGelirGiderYaz
go--
CREATE  PROCEDURE [dbo].[spGelirGiderYaz]   
   @BORC float,  
   @ALACAK float,  
   @ACIKLAMA nvarchar(50),  
   @GELGIDKODU nvarchar(30),  
   @GELGIDADI nvarchar(150),  
   @MUSNO int,  
   @MUSADI nvarchar(50),  
   @TARIH datetime,  
   @BA nvarchar(1),  
   @BAACIKLA nvarchar(12),  
   @KODU nvarchar(5),  
   @ISLEMNO int,  
   @MUSKOD nvarchar(20),  
   @DOVIZTUT float,  
   @DOVIZCINSI int,  
   @DOVIZKODU nvarchar(2),  
   @KASAADI nvarchar(10),  
   @KASAKODU nvarchar(6),  
   @KULNO int,  
   @KULADI nvarchar(20),  
   @AcikKapali nvarchar(3),  
   @DovizBorc float,  
   @DovizAlacak float,  
   @VardiyaKodu nvarchar(15),  
   @VardiyaDurumu nvarchar(9),  
   @Departman nvarchar(8),  
   @HesapKodu nvarchar(25),  
   @HesapAdi nvarchar(50),  
   @KarsiHesp nvarchar(5),  
   @KayitDuzeyi int,  
   @BelgeNo nvarchar(30),  
   @OzelKod1 nvarchar(10),  
   @OzelKod2 nvarchar(10),  
   @IsIstasyonKodu nvarchar(30),  
   @IsIstasyonAdi nvarchar(30),  
   @VardiyaNo nvarchar(8),  
   @BordroNosu int,  
   @BordroAciklamasi nvarchar(100),  
   @Modul nvarchar(3),      
   @SaticiKodu nvarchar(10),  
   @SaticiAdi nvarchar(25),  
   @Tutar float,  
   @KdvTutari float,  
   @Kdv float,  
   @StopajTutari float,  
   @Stopaj float,  
   @FisNo int,
   @DovizKuru float
AS  
  
 INSERT GELGID VALUES ( @BORC, @ALACAK, @ACIKLAMA,  
    @GELGIDKODU, @GELGIDADI, @MUSNO,  
    @MUSADI,@TARIH, @BA,@BAACIKLA,  
    @KODU, @ISLEMNO,@MUSKOD,@DOVIZTUT,  
    @DOVIZCINSI,@DOVIZKODU, @KASAADI,  
    @KASAKODU,@KULNO,@KULADI,@AcikKapali,  
    @DovizBorc,@DovizAlacak,@VardiyaKodu,  
    @VardiyaDurumu, @Departman,@HesapKodu,  
    @HesapAdi,@KarsiHesp,@KayitDuzeyi,  
    @BelgeNo,@OzelKod1,@OzelKod2,@IsIstasyonKodu,  
    @IsIstasyonAdi,@VardiyaNo,@BordroNosu, @BordroAciklamasi,  
    @Modul,@SaticiKodu,@SaticiAdi,@Tutar,@KdvTutari,@Kdv,@StopajTutari,@Stopaj, @FisNo,@DovizKuru)  
go--
if exists (select * from sys.procedures where name='StokKodAdDegistir')
drop proc StokKodAdDegistir
go--
create     procedure StokKodAdDegistir           
@STOKADI nvarchar(500),          
@STOKKODU nvarchar(40),          
@EskiStokKodu nvarchar(40),         
@STOKADI2 nvarchar(40) = ''      
as          
begin Transaction             
 UPDATE STOKHAR SET StokAdi = @STOKADI, StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE MuadilStoklar SET MuadilStokAdi = @STOKADI, MuadilStokKodu= @STOKKODU where MuadilStokKodu= @EskiStokKodu          
 UPDATE StokFiyat SET Kodu= @STOKKODU where Kodu= @EskiStokKodu          
 UPDATE StokDB SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE StokFiyatLog SET Kodu= @STOKKODU where Kodu= @EskiStokKodu          
 UPDATE StokMarkalari SET StokKodu= @STOKKODU where StokKodu=@EskiStokKodu          
 UPDATE Tedarikciler SET StokAdi = @STOKADI, StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE PYazarKasaStoklari SET StokAdi = @STOKADI, StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE PYazarKasaHar SET StokAdi = @STOKADI, StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE PPetrolHar SET StokAdi = @STOKADI, StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE PDegFiyatlar SET StokAdi = @STOKADI, StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE DonemselFiyatListesi SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE TekstilHareketTablosu SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE TekstilHataHareketTablosu SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE TekstilHataliStokVirmanSablonu SET HataliStokKodu= @STOKKODU where HataliStokKodu= @EskiStokKodu          
 UPDATE TekstilHataliStokVirmanSablonu SET VirmanStokKodu= @STOKKODU where VirmanStokKodu= @EskiStokKodu          
 UPDATE TekstilIsEmirleriDetayi SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE TekstilKesimTablosu SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE TekstilStokRenkTanimlari SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE CariUretimFiyatlari SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE Seri SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE Tarim_AmbalajStok SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 UPDATE Tarim_AmbalajStok SET AmbalajKodu= @STOKKODU where AmbalajKodu= @EskiStokKodu          
 UPDATE StokDB SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu          
 update MH_Connect SET Degeri =@STOKKODU where Degeri=@EskiStokKodu and TabloAdi='STOKKARTI' and FieldAdi='Kodu'          
 Update StokTablolari   Set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu            
 Update Tarim_AmbalajStok  Set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu            
 Update Tarim_AmbalajStok  Set AmbalajKodu=@STOKKODU Where AmbalajKodu=@EskiStokKodu            
 Update Tarim_SatisEmirleri  Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu            
 Update Tarim_UretimDetay  Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu            
 Update Tarim_UretimDetay  Set KasaKodu=@STOKKODU Where KasaKodu=@EskiStokKodu            
 Update Tarim_UretimDetay  Set PaletKodu=@STOKKODU Where PaletKodu=@EskiStokKodu            
 Update Tarim_UretimDetay2  Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu            
 Update Tarim_UrunAlim   Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu            
 Update Tarim_UrunAlimAmbalaj Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu            
 Update Tarim_UrunAlimHareket Set KasaKodu=@STOKKODU Where KasaKodu=@EskiStokKodu            
 Update Tarim_UrunAlimHareket Set PaletKodu=@STOKKODU Where PaletKodu=@EskiStokKodu            
 Update StokTartim    Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu            
 Update StokTartimPalet   Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu           
 Update CariDonemFiyatlari set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu           
 Update ElTerminaliDepoSayim set StokKodu=@STOKKODU, StokAdi=@STOKADI  Where StokKodu=@EskiStokKodu           
 Update ElTerminaliYukleme set StokKodu=@STOKKODU, StokAdi=@STOKADI  Where StokKodu=@EskiStokKodu           
 Update EtiketBarkod set StokKodu=@STOKKODU, StokAdi=@STOKADI  Where StokKodu=@EskiStokKodu           
 Update MiktarsalHedefler set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu           
 Update RenkBedenSeriTablosu set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu           
 Update RenkBedenTablosu set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu           
 Update SIPARISHAR set StokKodu=@STOKKODU, StokAdi=@STOKADI  Where StokKodu=@EskiStokKodu           
 Update TEKLIFHAR set StokKodu=@STOKKODU, StokAdi=@STOKADI  Where StokKodu=@EskiStokKodu             
 Update SeriNoKaliteKontrol set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu           
 Update SipHar set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu         
 Update StokDepoMiktarlari set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu           
 Update StokVergiMuafiyetleri set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu           
 UPDATE InvoiceItemMap SET OurCode = @STOKKODU,SenderItemName = @STOKADI where OurCode = @EskiStokKodu          
 UPDATE STOKKARTI SET Kodu= @STOKKODU, StokAdi=@STOKADI,StokAdi2 = @STOKADI2 where Kodu= @EskiStokKodu       
 Update StokBarkodlari set StokKodu=@STOKKODU  Where StokKodu=@EskiStokKodu      
 Update StokBarkodlari set Barkodu=@STOKKODU  Where Barkodu=@EskiStokKodu         
        
commit; 
go--
IF NOT EXISTS (SELECT *  FROM sys.tables WHERE  name='FaturaFiyatGuncellemeFarki')
 BEGIN 
CREATE TABLE [dbo].[FaturaFiyatGuncellemeFarki](
	[NoId] [int] IDENTITY(1,1) NOT NULL,
	[IslemNo] [int] NULL,
	[Tarih] [datetime] NULL,
	[EskiTutar] [float] NULL,
	[YeniTutar] [float] NULL,
	[StokNo] [int] NULL,
 CONSTRAINT [PK_FaturaFiyatGuncellemeFarki] PRIMARY KEY CLUSTERED 
(
	[NoId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
end
go--
IF  EXISTS (SELECT *  FROM sys.views WHERE  name='V_FaturaFiyatGuncelleme')
 BEGIN 
 drop view V_FaturaFiyatGuncelleme
 end
go--
CREATE    VIEW V_FaturaFiyatGuncelleme 
AS
	select F.Tarih,F.IslemNo ,round(F.EskiTutar*(100+SF.SatisKdv )/100*S.FaturaMiktari,2)EskiTutar ,
	round (F.YeniTutar*(100+SF.SatisKdv )/100*S.FaturaMiktari,2) YeniTutar,   
	round((YeniTutar-EskiTutar)*(100+SF.SatisKdv )/100*S.FaturaMiktari,2) Fark,
	S.StokKodu,
	S.StokAdi,
	S.CariKodu,
	A.MUSADI Cari_Adi,
	S.FaturaTarihi
	from FaturaFiyatGuncellemeFarki    F 
	LEFT JOIN STOKHAR S ON S.IslemNo=F.IslemNo 
	LEFT JOIN AMUSTERI A ON A.MUSKOD=S.CariKodu 
	LEFT JOIN StokFiyat SF ON SF.Kodu=S.StokKodu WHERE S.IslemNo=F.IslemNo AND S.CariNo = A.MUSNO and S.StokNo=F.StokNo
go--
if exists (select * from sys.procedures where name='sp_Prk_Satis_Cevirme_Tekli')
drop proc sp_Prk_Satis_Cevirme_Tekli
go--
create  procedure sp_Prk_Satis_Cevirme_Tekli  
(@IslemNo int,            
 @FaturaTarihi smalldatetime,  
 @FaturaNo integer,  
 @FatSerNo nvarchar(50),
 @YazarKasaFisNo integer,
 @FaturaTipi integer
)                  
as  
begin
	update STOKHAR SET  IslemTuru= 'Satış',FaturaTarihi = @FaturaTarihi where IslemNo = @IslemNo;
	update STOKHARDETBAG SET	
		   IslemTuru='Satış',
		   FaturaTarihi= @FaturaTarihi ,
		   FatSerNo=@FatSerNo ,
		   FaturaNo= @FaturaNo,
		   YazarKasaFisNo = @YazarKasaFisNo,
		   FaturaTipi =  @FaturaTipi
		   where IslemNo = @IslemNo;                                                     
	update dbo.ACARI  SET ACIKLAMA=  @FaturaNo + ' no.lu Fatura',BAACIKLA = 'Satış', TARIH = @FaturaTarihi where ISLEMNO = @IslemNo;        
    update Odeme SET BAAcikla='Satış', Tarih =  @FaturaTarihi where IslemNo = @IslemNo;                      
end;
go--
if exists (select * from sys.procedures where name='sp_AdresStokHareketRap')
drop proc sp_AdresStokHareketRap
go--
      				   
CREATE  PROCEDURE sp_AdresStokHareketRap
(@CariKodu nvarchar(25),
 @SevkTarihi1 smalldatetime,
 @SevkTarihi2 smalldatetime,
 @AdresNo int
)
AS
SELECT IslemNo,
	   IslemTuru,
	   FaturaNo,
	   eFaturaNo,
	   FaturaTarihi,
	   SevkTarihi,
	   CAST(AdresNo as nvarchar(10))+ ' - ' + Adres1 + ' ' + Adres2 + ' İl - İlçe : ' + Il + ' ' + Ilce Adres,
	   Tutar,
	   Aciklama,
	   DovizKodu,
	   DovizKur
  FROM STOKHARDETBAG db,Adres adr
 WHERE db.CariNo = adr.CariNo
   AND db.SevkAdresNo = adr.AdresNo
   AND db.CariKodu = @CariKodu
   AND ((@SevkTarihi1 IS NULL) OR (db.SevkTarihi >= @SevkTarihi1))
   AND ((@SevkTarihi2 IS NULL) OR (db.SevkTarihi <= @SevkTarihi2))
   AND ((@AdresNo IS NULL) OR (AdresNo = @AdresNo))
ORDER BY FaturaTarihi DESC
go--
      				   
if exists (select * from sys.procedures where name='StokNo_Update')
drop proc StokNo_Update
go--
      				   
CREATE  PROC StokNo_Update(@Degistir bit = 0)
AS 
BEGIN
	IF @Degistir = 1
	BEGIN
		UPDATE n  SET StokNo = k2.SIRA  FROM STOKKARTI  n , (select Kodu,StokNo,NoId,RANK () OVER (order  BY   Kodu DESC) SIRA FROM STOKKARTI) k2 where n.Kodu=k2.Kodu 
	END;

	UPDATE n  SET StokNo = k2.StokNo  FROM STOKHAR  n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu 
	UPDATE n  SET StokNo = k2.StokNo  FROM SIPARISHAR   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu 
	UPDATE n  SET StokNo = k2.StokNo  FROM StokBarkodlari   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu 
	UPDATE n  SET StokNo = k2.StokNo  FROM StokFiyat   n ,  STOKKARTI k2 where n.Kodu =k2.Kodu 
	UPDATE n  SET StokNo = k2.StokNo  FROM StokDB   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu 
	UPDATE n  SET StokNo = k2.StokNo  FROM StokHarLog   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu 
	UPDATE n  SET StokNo = k2.StokNo  FROM MuadilStoklar   n ,  STOKKARTI k2 where n.MuadilStokKodu =k2.Kodu 
	UPDATE n  SET StokNo = k2.StokNo  FROM Buton   n ,  STOKKARTI k2 where n.ButonDegeri =k2.Kodu 
	UPDATE n  SET StokNo = k2.StokNo  FROM PDegFiyatlar   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu 
	UPDATE n  SET StokNo = k2.StokNo  FROM SipHar   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu 
	UPDATE n  SET StokNo = k2.StokNo  FROM TEKLIFHAR   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu 
	UPDATE n  SET StokNo = k2.StokNo  FROM Tevkifat   n ,  STOKKARTI k2 where n.Kod =k2.Kodu 	
--- FaturaFiyatGuncellemeFarki -StokHarLog -Tedarikciler TABLOLARI KONTROL ET
END;
go--
      				   
if exists (select * from sys.procedures where name='sp_StokFiyat_Fiyat_FiyatH_Kodlu')
drop proc sp_StokFiyat_Fiyat_FiyatH_Kodlu
go--
      				   
CREATE PROCEDURE sp_StokFiyat_Fiyat_FiyatH_Kodlu
 @GelenStokKodu nvarchar(30),            
 @FiyatAdi nvarchar(30),            
 @Fiyat decimal(18,8),          
 @DovizKodu nvarchar(3),
 @KdvDHGuncelle bit = 0,
 @KdvDH char(1)
 /*@Iskonto1 float = 0,     
 @Iskonto2 float = 0,     
 @Iskonto3 float = 0,     
 @Iskonto4 float = 0  ,  
 @IskontoGuncelle bit = 0,*/
as          
begin      
 DECLARE @DovizKuru float      
 DECLARE @Query nvarchar(max),@Fyt nvarchar(3)      
    DECLARE @ResultDovizKodu nvarchar(3)      
      
 IF LEN(@FiyatAdi) = 7      
  SET @Fyt = SUBSTRING(@FiyatAdi,1,2)      
    ELSE       
  SET @Fyt = SUBSTRING(@FiyatAdi,1,3);      
      
 if @DovizKodu =''      
 BEGIN      
  SET @Query = 'select @DovizKod = '+@Fyt+'DovizKodu from StokFiyat where Kodu = '''+@GelenStokKodu+'''';       
  EXEC sp_executesql @Query,      
         N'@DovizKod nvarchar(3) OUTPUT',      
          @DovizKod = @ResultDovizKodu OUTPUT ;      
 SET @DovizKodu =  @ResultDovizKodu;      
 END;      
      
 SET @DovizKuru = (Select GunFiyati from DOVIZT where DovizKodu = @DovizKodu)      
 SET @Fiyat = @Fiyat / @DovizKuru;      

 IF @KdvDHGuncelle = 1 
 BEGIN
	SET @Query = 'UPDATE StokFiyat SET  '+@Fyt+'Kdv =  '''+@KdvDH+''' where Kodu = '''+@GelenStokKodu+''''; 
	EXEC sp_executesql @Query;	
 END

 SET @Query = 'UPDATE StokFiyat SET  '+@Fyt+'Fiyat =  '+CAST(@Fiyat as nvarchar(50))+' where Kodu = '''+@GelenStokKodu+'''';   
 EXEC sp_executesql @Query;
 SET @Query = 'UPDATE StokFiyat SET '+@Fyt+'FiyatH = (CASE WHEN '+@Fyt+'Kdv = ''H'' THEN '+CAST(@Fiyat as nvarchar(50))+' ELSE ('+CAST(@Fiyat as nvarchar(50))+'/(100+SatisKdv))*100 END), '+@Fyt+'DovizKodu='''+@DovizKodu+''' where Kodu =''' + @GelenStokKodu
 + '''';      
 EXEC sp_executesql @Query;          
 IF @Fyt in ('F1','F2','F3','F4')      
 BEGIN     
  UPDATE sk SET sk.F1Fiyat  = sf.F1Fiyat, sk.F1DovizKodu = sf.F1DovizKodu,  sk.F1Kdv = sf.F1Kdv,    
       sk.F2Fiyat  = sf.F2Fiyat, sk.F2DovizKodu = sf.F2DovizKodu,  sk.F2Kdv = sf.F2Kdv,   
       sk.F3Fiyat  = sf.F3Fiyat, sk.F3DovizKodu = sf.F3DovizKodu,  sk.F3Kdv = sf.F3Kdv,   
       sk.F4Fiyat  = sf.F4Fiyat, sk.F4DovizKodu = sf.F4DovizKodu,  sk.F4Kdv = sf.F4Kdv
       /*sk.AlisIndirimYuzde  =  (CASE WHEN @IskontoGuncelle = 1 THEN @Iskonto1 ELSE sk.AlisIndirimYuzde END),    
       sk.AlisIndirimYuzde2 =  (CASE WHEN @IskontoGuncelle = 1 THEN @Iskonto2 ELSE sk.AlisIndirimYuzde2 END),    
       sk.AlisIndirimYuzde3 =  (CASE WHEN @IskontoGuncelle = 1 THEN @Iskonto3 ELSE sk.AlisIndirimYuzde3 END),     
       sk.AlisIndirimYuzde4 =  (CASE WHEN @IskontoGuncelle = 1 THEN @Iskonto4 ELSE sk.AlisIndirimYuzde4 END) */   
     FROM  STOKKARTI sk,StokFiyat sf WHERE sk.Kodu = sf.Kodu and sk.Kodu = @GelenStokKodu      
 END; 
END;
go--
      				   
if exists (select * from sys.procedures where name='sp_StokFiyat_Fiyat_FiyatH')
drop proc sp_StokFiyat_Fiyat_FiyatH
go--
      				   
CREATE  PROCEDURE sp_StokFiyat_Fiyat_FiyatH   
AS      
begin      
 declare @i int,@sorgu nvarchar(max),@cnt nvarchar(2)      
 set @i = 1;      
    while @i <= 20       
 begin      
   SET @cnt = CAST(@i as varchar(2));      
   SET @sorgu = ' UPDATE StokFiyat SET  F'+@cnt+'FiyatH = CASE WHEN F'+@cnt+'Kdv = ''H'' THEN F'+@cnt+'Fiyat ELSE (F'+@cnt+'Fiyat/(100 + SatisKdv)*100) END';      
   -- print @sorgu      
   EXEC sp_executesql @sorgu;      
   SET @i += 1;      
    end;      
      
 UPDATE sk SET sk.F1Fiyat  = sf.F1Fiyat, sk.F1DovizKodu = sf.F1DovizKodu,  sk.F1Kdv = sf.F1Kdv,    
       sk.F2Fiyat  = sf.F2Fiyat, sk.F2DovizKodu = sf.F2DovizKodu,  sk.F2Kdv = sf.F2Kdv,   
       sk.F3Fiyat  = sf.F3Fiyat, sk.F3DovizKodu = sf.F3DovizKodu,  sk.F3Kdv = sf.F3Kdv,   
       sk.F4Fiyat  = sf.F4Fiyat, sk.F4DovizKodu = sf.F4DovizKodu,  sk.F4Kdv = sf.F4Kdv  
     FROM  STOKKARTI sk,StokFiyat sf WHERE sk.Kodu = sf.Kodu       
end;  
go--

if  not  exists (select * from dbo.syscolumns where id = object_id(N'AnaMenuAyar') and name=N'ComputerName')
begin
ALTER TABLE AnaMenuAyar ADD ComputerName nvarchar(50)
end
else begin
ALTER TABLE AnaMenuAyar alter column ComputerName nvarchar(50)
end
go--

if  not  exists (select * from dbo.syscolumns where id = object_id(N'AcariTakas') and name=N'TeslimEden')
begin
ALTER TABLE AcariTakas ADD TeslimEden nvarchar(150)
end
else begin
ALTER TABLE AcariTakas alter column TeslimEden nvarchar(150)
end
go--
if  not  exists (select * from dbo.syscolumns where id = object_id(N'AcariTakas') and name=N'TeslimAlan')
begin
ALTER TABLE AcariTakas ADD TeslimAlan nvarchar(150)
end
else begin
ALTER TABLE AcariTakas ALTER COLUMN TeslimAlan nvarchar(150)
end
go--
if  not  exists (select * from dbo.syscolumns where id = object_id(N'AcariTakas') and name=N'Aciklama2')
begin
ALTER TABLE AcariTakas ADD Aciklama2 nvarchar(400)
end
else begin
ALTER TABLE AcariTakas ALTER COLUMN Aciklama2 nvarchar(400)
end
go--


if exists (select * from sys.procedures where name='FaturaFisFiyatGuncelle')
drop proc FaturaFisFiyatGuncelle
go--
CREATE  procedure FaturaFisFiyatGuncelle @muskod varchar(20),@Tar1 varchar(8),@Tar2 varchar(8)      
as    
--declare @muskod varchar(10)    
--declare @Tar1 varchar(8)    
--declare @Tar2 varchar(8)    
    
--set @muskod='M0002'    
--set @Tar1='20210301'    
--set @Tar2='20220301'    
    
begin        
declare @TopTutar float         
declare @tutar float        
declare @ttutar float        
declare @noids varchar(max)        
declare @noid int        
        
select @TopTutar=MUSBAKIYE from V_AMUSTERI where MUSKOD = @muskod        
        
set @TopTutar=@TopTutar        
    
--print 'Toptutar='    
--print @TopTutar    
    
update STOKHARDETBAG set SecimEH = 'H' where CariKodu=@muskod        
        
declare FaturaFisCursor2 Cursor         
for        
select NoId,Tutar from STOKHARDETBAG         
where CariKodu = @muskod and         
IslemTuru in( 'Prk.Satış','Satış') and         
FaturaTarihi>=@Tar1 and     
FaturaTarihi<=@Tar2 and    
FisTuru='F' and IslemNo in(        
select ISLEMNO from ACARI where not exists (select * from KASA where KASA.ISLEMNO=ACARI.ISLEMNO)        
and MUSNO=STOKHARDETBAG.CariNo)        
order by FaturaTarihi desc         
        
open FaturaFisCursor2;        
        
fetch next from FaturaFisCursor2 into @noid,@tutar        
        
set @ttutar = 0;        
set @noids ='0';        
        
declare @dur int        
set @dur=0        
        
WHILE (@@FETCH_STATUS = 0)and(@dur=0)        
  Begin        
   set @ttutar = @ttutar + @tutar        
   print @ttutar        
        
   if (@TopTutar>=@ttutar)        
     begin        
    set @noids = @noids+',<'+cast(@noid as varchar)+'>'           
    fetch next from FaturaFisCursor2 into @noid,@tutar        
  end        
    else        
     Set @dur = 1        
  end        
        
print 'noids='+@noids        
        
close FaturaFisCursor2         
        
deallocate FaturaFisCursor2         
        
update STOKHARDETBAG set SecimEH ='E' where        
charindex('<'+cast(NoId as varchar)+'>',@noids)>0        
        
select sum(Tutar)as toplam     
 from STOKHARDETBAG         
where CariKodu = @muskod and         
IslemTuru in( 'Prk.Satış','Satış') and         
FaturaTarihi>=@Tar1 and          
FaturaTarihi<=@Tar2 and        
FisTuru='F' and IslemNo in(        
select ISLEMNO from ACARI where not exists (select * from KASA where KASA.ISLEMNO=ACARI.ISLEMNO)        
and MUSNO=STOKHARDETBAG.CariNo)       
and SecimEH='E'      
end    
go--
IF NOT EXISTS (SELECT *  FROM sys.tables WHERE  name='FaturaFiyatGuncellemeKontrol')
 BEGIN 
CREATE TABLE [dbo].[FaturaFiyatGuncellemeKontrol](
	[NoId] [int] IDENTITY(1,1) NOT NULL,
	[StokKodu] [nvarchar](25) NULL,
	[StokAdi] [nvarchar](500) NULL,
	[EskiFiyat] [float] NULL,
	[YeniFiyat] [float] NULL,
	[Tarih] [smalldatetime] NULL,
	[KullaniciNo] [int]
) ON [PRIMARY]
end
go--
IF NOT EXISTS (SELECT *  FROM sys.tables WHERE  name='BakiyeKapatmaParametre')
 BEGIN 
CREATE TABLE [dbo].[BakiyeKapatmaParametre](
	[NoId] [int] IDENTITY(1,1) NOT NULL,
	[Gun1] [int] NULL,
	[Gun2] [int] NULL,
	[KolonAdi] [nvarchar](50) NULL,
	[Tarih] [smalldatetime] NULL,
	[KullaniciNo] [int] NULL
) ON [PRIMARY]
end

go--
UPDATE Adres SET AdresNo = 10 where AdresNo = 0 
go--
UPDATE a  SET a.AdresNo = tbl.SiraNo from 
	(select CariNo,AdresNo,NoId,RANK () OVER (PARTITION BY CariNo order  BY  AdresNo,NoId) SiraNo from Adres) tbl,Adres a
where a.NoId = tbl.NoId
go--
if exists (select * from sys.procedures where name='StokKartiBirlestir')
drop proc StokKartiBirlestir
go--
create       procedure StokKartiBirlestir(  
@EskiStokKodu nvarchar(40),  
@EskiStokAdi nvarchar(500),           
@EskiStokNo int,  
@YeniStokKodu nvarchar(40),  
@YeniStokAdi nvarchar(500),           
@YeniStokNo int)      
as              
begin                 
 UPDATE STOKHAR SET StokAdi = @YeniStokAdi, StokKodu= @YeniStokKodu,StokNo = @YeniStokNo where StokKodu= @EskiStokKodu      
 UPDATE StokFiyatLog SET Kodu= @YeniStokKodu where Kodu= @EskiStokKodu              
 UPDATE PDegFiyatlar SET StokAdi = @YeniStokAdi, StokKodu= @YeniStokKodu where StokKodu= @EskiStokKodu  
 UPDATE PPetrolHar SET StokAdi = @YeniStokAdi, StokKodu= @YeniStokKodu where StokKodu= @EskiStokKodu      
 UPDATE PYazarKasaStoklari SET StokAdi = @YeniStokAdi, StokKodu= @YeniStokKodu where StokKodu= @EskiStokKodu              
 UPDATE PYazarKasaHar SET StokAdi = @YeniStokAdi, StokKodu= @YeniStokKodu where StokKodu= @EskiStokKodu    
 UPDATE DonemselFiyatListesi SET StokKodu= @YeniStokKodu where StokKodu= @EskiStokKodu    
 --DELETE MuadilStoklar WHERE MuadilStokKodu = @EskiStokKodu  
 --UPDATE MuadilStoklar SET MuadilStokAdi = @STOKADI, MuadilStokKodu= @STOKKODU where MuadilStokKodu= @EskiStokKodu                         
 UPDATE CariUretimFiyatlari SET StokKodu= @YeniStokKodu where StokKodu= @EskiStokKodu    
 UPDATE Seri SET StokKodu= @YeniStokKodu where StokKodu= @EskiStokKodu     
 Update CariDonemFiyatlari set StokKodu=@YeniStokKodu Where StokKodu=@EskiStokKodu       
 Update ElTerminaliDepoSayim set StokKodu=@YeniStokKodu, StokAdi=@YeniStokAdi  Where StokKodu=@EskiStokKodu     
 Update ElTerminaliYukleme set StokKodu=@YeniStokKodu, StokAdi=@YeniStokAdi  Where StokKodu=@EskiStokKodu       
 Update EtiketBarkod set StokKodu=@YeniStokKodu, StokAdi=@YeniStokAdi  Where StokKodu=@EskiStokKodu             
 Update MiktarsalHedefler set StokKodu=@YeniStokKodu Where StokKodu=@EskiStokKodu         
 Update RenkBedenSeriTablosu set StokKodu=@YeniStokKodu Where StokKodu=@EskiStokKodu            
 Update RenkBedenTablosu set StokKodu=@YeniStokKodu Where StokKodu=@EskiStokKodu               
 Update SIPARISHAR set StokKodu=@YeniStokKodu, StokAdi=@YeniStokAdi,StokNo = @YeniStokNo  Where StokKodu=@EskiStokKodu              
 Update TEKLIFHAR set StokKodu=@YeniStokKodu, StokAdi=@YeniStokAdi,StokNo = @YeniStokNo  Where StokKodu=@EskiStokKodu       
 Update StokDepoMiktarlari set StokKodu=@YeniStokKodu Where StokKodu=@EskiStokKodu      
 UPDATE InvoiceItemMap SET OurCode = @YeniStokKodu,SenderItemName = @YeniStokAdi where OurCode = @EskiStokKodu       
 DELETE StokBarkodlari Where StokKodu=@EskiStokKodu          
 DELETE StokDB where StokKodu= @EskiStokKodu     
 DELETE StokTablolari Where StokKodu=@EskiStokKodu     
 DELETE StokVergiMuafiyetleri Where StokKodu=@EskiStokKodu    
 DELETE StokDB where StokKodu= @EskiStokKodu   
 DELETE StokMarkalari where StokKodu=@EskiStokKodu              
 DELETE Tedarikciler where StokKodu= @EskiStokKodu        
 DELETE StokFiyat where Kodu= @EskiStokKodu   
 DELETE STOKKARTI where Kodu= @EskiStokKodu   
 DELETE MH_Connect where Degeri=@EskiStokKodu and TabloAdi='STOKKARTI' and FieldAdi='Kodu'          
END; 
go--
if exists (select * from sys.procedures where name='CariKartiBirlestir')
drop proc CariKartiBirlestir
go--
create      procedure CariKartiBirlestir(
@EskiCariKodu nvarchar(40),
@EskiCariAdi nvarchar(500),         
@EskiCariNo int,
@YeniCariKodu nvarchar(40),
@YeniCariAdi nvarchar(500),         
@YeniCariNo int)    
AS            
BEGIN
	 UPDATE ACARI SET MUSADI = @YeniCariAdi, MUSKOD= @YeniCariKodu,MUSNO = @YeniCariNo where MUSNO = @EskiCariNo   
	 UPDATE Odeme SET CariKodu= @YeniCariKodu,CariNo = @YeniCariNo where CariNo = @EskiCariNo  
	 UPDATE STOKHAR SET CariAdi = @YeniCariAdi, CariKodu= @YeniCariKodu,CariNo = @YeniCariNo where CariNo = @EskiCariNo    
	 UPDATE STOKHARDETBAG SET CariAdi = @YeniCariAdi, CariKodu= @YeniCariKodu,CariNo = @YeniCariNo where CariNo = @EskiCariNo    
	 UPDATE BANKA SET MUSADI = @YeniCariAdi, MusKod= @YeniCariKodu,MUSNO = @YeniCariNo where MUSNO = @EskiCariNo    
	 UPDATE KASA SET MUSADI = @YeniCariAdi, MUSKOD= @YeniCariKodu,MUSNO = @YeniCariNo where MUSNO = @EskiCariNo    
	 UPDATE CEK SET MUSADI = @YeniCariAdi, MUSKODU= @YeniCariKodu,MUSNO = @YeniCariNo where MUSNO = @EskiCariNo    
	 UPDATE BORDRO SET MUSADI = @YeniCariAdi, MUSKODU= @YeniCariKodu,MUSNO = @YeniCariNo where MUSNO = @EskiCariNo      
	 UPDATE DonemselFiyatListesiCari SET CariKodu =  @YeniCariKodu where CariKodu = @EskiCariKodu      
	 UPDATE TEKLIFHAR SET CariAdi = @YeniCariAdi, CariKodu= @YeniCariKodu,CariNo = @YeniCariNo where  CariNo=@EskiCariNo    
	 UPDATE TEKLIFHARDETBAG SET CariAdi = @YeniCariAdi, CariKodu= @YeniCariKodu,CariNo = @YeniCariNo where  CariNo=@EskiCariNo   
	 UPDATE CariNotlar set CariKodu=@YeniCariKodu where CariKodu = @EskiCariKodu  
	 UPDATE FaturaDetay set CariKodu=@YeniCariKodu where CariKodu = @EskiCariKodu    
	 UPDATE OdemeSozu set CariAdi = @YeniCariAdi, CariKodu= @YeniCariKodu where CariKodu = @EskiCariKodu    
	 UPDATE PPlaka set CariKodu=@YeniCariKodu where CariKodu = @EskiCariKodu  
	 UPDATE SIPARISHAR set CariAdi = @YeniCariAdi, CariKodu= @YeniCariKodu,CariNo = @YeniCariNo where CariNo = @EskiCariNo    
	 UPDATE SIPARISHARDETBAG set CariAdi = @YeniCariAdi, CariKodu= @YeniCariKodu,CariNo = @YeniCariNo where CariNo = @EskiCariNo    
	 UPDATE TelAramaLog set CariKodu=@YeniCariKodu where CariKodu = @EskiCariKodu    
	 UPDATE Ziyaret set CariKodu=@YeniCariKodu where CariKodu = @EskiCariKodu     
	 DELETE FirinFiyatListesi WHERE CariKodu = @EskiCariKodu   
	 DELETE CariUretimFiyatlari WHERE CariKodu = @EskiCariKodu   
	 DELETE CariSozlesme WHERE CariKodu = @EskiCariKodu   
	 DELETE CariReferanslar WHERE CariKodu = @EskiCariKodu   
	 DELETE CariBarkodlari WHERE CariKodu = @EskiCariKodu 
	 DELETE Bonus WHERE CariKodu = @EskiCariKodu 
	 DELETE Rut WHERE CariKodu = @EskiCariKodu  
	 DELETE Satici WHERE CariKodu = @EskiCariKodu
	 DELETE Adres WHERE CariNo = @EskiCariNo
	 DELETE AMUSTERI WHERE MUSNO=@EskiCariNo    
END;         
go--
if exists (select * from sys.procedures where name='sp_Bakim_Doviz_KdvDH_Update')
drop proc sp_Bakim_Doviz_KdvDH_Update
go--
CREATE PROCEDURE sp_Bakim_Doviz_KdvDH_Update
AS
BEGIN
	declare @DovizKod nvarchar(5),@KdvDH nvarchar(1)
	declare @i int,@sorgu nvarchar(max),@cnt nvarchar(2) 

	IF (select count(*) from DOVIZT where DovizKodu = 'YP') > 0 
		SET @DovizKod = 'YP'
	ELSE IF  (select count(*) from DOVIZT where DovizKodu = 'TL') > 0
		SET @DovizKod = 'TL'
	ELSE 
		select TOP 1  @DovizKod = DovizKodu from DOVIZT ORDER BY NoId 
       
	SET @i = 1;        
	WHILE @i <= 20         
	BEGIN        
	   SET @cnt = CAST(@i as varchar(2));        
	   SET @sorgu = ' UPDATE StokFiyat SET  F'+@cnt+'DovizKodu = ''' + @DovizKod + ''' WHERE  ISNULL(F'+@cnt+'DovizKodu,'''') = '''''               
	   EXEC sp_executesql @sorgu;   
	   SET @i += 1;        
	END;        

	UPDATE StokFiyat SET F4Kdv = 'D' WHERE ISNULL(F4Kdv,'') = '' 
	UPDATE StokFiyat SET F2Kdv = 'H' WHERE ISNULL(F2Kdv,'') = '' 
 
	UPDATE sk SET sk.F1DovizKodu = sf.F1DovizKodu,   
				sk.F2DovizKodu = sf.F2DovizKodu,  
				sk.F3DovizKodu = sf.F3DovizKodu,  
				sk.F4DovizKodu = sf.F4DovizKodu,
				sk.F2Kdv		  = sf.F2Kdv,
				sk.F4Kdv		  = sf.F4Kdv
		FROM  STOKKARTI sk,StokFiyat sf WHERE sk.Kodu = sf.Kodu      
END;
go--
if exists (select * from sys.procedures where name='sp_SN_Bakim')
drop proc sp_SN_Bakim
go--
CREATE   PROC sp_SN_Bakim      
AS  
BEGIN       
 EXEC sp_Grup_Bakim        
 EXEC sp_StokDoviz_Bakim        
 EXEC  sp_StokFiyat_Bakim        
 EXEC sp_StokFiyatBakim         
 EXEC sp_Kart_Bakim      
 EXEC sp_BAKIM_KOLON_UPDATE    
 EXEC sp_Hareket_Bakim  
 EXEC sp_BirimBarkod_Aktarim  
 EXEC sp_Bakim_Doviz_KdvDH_Update
 exec sp_OdemePlaniKontrol 
END  
go--
IF NOT EXISTS (SELECT *  FROM sys.tables WHERE  name='StokDepoRafTanimlari')
 BEGIN 
CREATE TABLE [dbo].[StokDepoRafTanimlari](
	[NoId] [int] IDENTITY(1,1) NOT NULL,
	[StokNo] [int] NULL,
	[DepoNoId] int NULL,
	[RafNo] nvarchar(50) NULL,
	[KulNo] [int] NOT NULL,
	[UpdateDate] [datetime] NOT NULL,	
 CONSTRAINT [PK_StokDepoRafTanimlari] PRIMARY KEY CLUSTERED 
(
	[NoId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[StokDepoRafTanimlari] ADD  DEFAULT ((1)) FOR [KulNo]

ALTER TABLE [dbo].[StokDepoRafTanimlari] ADD  DEFAULT (getdate()) FOR [UpdateDate]

end
go--
      				   
if exists (select * from sys.procedures where name='sp_shrink')
drop proc sp_shrink
go--
CREATE  PROCEDURE sp_shrink (@dbname nvarchar(50))
AS
BEGIN
	DECLARE @sorgu nvarchar(max),@filename nvarchar(50)
   
	SET @sorgu = 'USE ' + @dbname
	EXEC sp_executesql @sorgu; 

	SET @sorgu = 'DBCC SHRINKDATABASE(N'''+@dbname+''')'; 
	EXEC sp_executesql @sorgu;   

	select @filename = name from sys.database_files where name like '%Data'

	SET @sorgu = 'DBCC SHRINKFILE (N'''+@filename+''' , 0, TRUNCATEONLY)'; 
	EXEC sp_executesql @sorgu;   

	select  @filename = name from sys.database_files where name like '%Log'
	SET @sorgu = 'DBCC SHRINKFILE (N'''+@filename+''' , 0, TRUNCATEONLY)'; 
	EXEC sp_executesql @sorgu;   
END;
go--
if exists (select * from sys.procedures where name='sp_Kart_Bakim')
drop proc sp_Kart_Bakim
go--
  create   proc sp_Kart_Bakim          
as          
 ALTER TABLE STOKKARTI ALTER COLUMN Barkodu  nvarchar(40)      
 UPDATE STOKKARTI SET Barkodu = Kodu where ISNULL(Barkodu,'') = ''      
  update StokBarkodlari set AnaBirim=0 where AnaBirim is null or AnaBirim='' or AnaBirim<>1          
  UPDATE StokBarkodlari SET Barkodu=StokKodu WHERE Barkodu IN ('',' ',NULL)        
          
----ÇİFT KAYIT STOKKARTLARI LİSTESİNİ VERİR.          
--select * from STOKKARTI SK1 WHERE Kodu in (SELECT Kodu FROM STOKKARTI group by Kodu having count(Kodu)>1)          
-- AND NoId =(SELECT MIN(NoId) FROM STOKKARTI SK3 where SK3.Kodu=SK1.Kodu)          
--select * from STOKKARTI SK1 WHERE Kodu in (SELECT Kodu FROM STOKKARTI group by Kodu having count(Kodu)>1)          
          
--ÇİFT KAYITLARDAN İLK AÇILANLARI SİLER. EN SON KAYIT KALIR.          
DELETE from STOKKARTI  WHERE Kodu in (SELECT Kodu FROM STOKKARTI group by Kodu having count(Kodu)>1)          
 AND NoId <>(SELECT max(NoId) FROM STOKKARTI SK3 where SK3.Kodu=STOKKARTI.Kodu)          
    --Stokfiyat Kodu  1 den fazla olan kayıtlardan son kayıt hariç siler         
DELETE from StokFiyat WHERE Kodu in (SELECT Kodu FROM StokFiyat group by Kodu having count(Kodu)>1)          
 AND NoId <>(SELECT max(NoId) FROM StokFiyat SK3 where SK3.Kodu= StokFiyat.Kodu)          
  --StokBarkodu 1 den fazla olan kayıtlardan son kayıt hariç siler         
DELETE from StokBarkodlari WHERE Barkodu in (SELECT Barkodu FROM StokBarkodlari group by Barkodu having count(Barkodu)>1)          
 AND StokBarkodlariNoId <>(SELECT max(StokBarkodlariNoId) FROM StokBarkodlari SK3 where SK3.Barkodu= StokBarkodlari.Barkodu)          
         
 --stokkartı olmayan stokfiyat'-Stokbarkodlari  silme          
 ---Tabloda karşılılğı olmayanları silme !!!          
DELETE FROM StokVergiMuafiyetleri WHERE NOT EXISTS (SELECT * FROM STOKKARTI WHERE Kodu=StokVergiMuafiyetleri.StokKodu)          
DELETE FROM StokFiyat  WHERE NOT EXISTS (SELECT * FROM STOKKARTI WHERE Kodu=StokFiyat.Kodu)          
DELETE FROM StokBarkodlari WHERE NOT EXISTS (SELECT * FROM STOKKARTI WHERE Kodu=StokBarkodlari.StokKodu)          
DELETE FROM StokDB WHERE NOT EXISTS (SELECT * FROM STOKKARTI WHERE Kodu=StokDB.StokKodu)     
  
UPDATE STOKKARTI SET IkinciBirimMiktari = 1 WHERE ISNULL(IkinciBirimMiktari,0) = 0 or IkinciBirimMiktari = ''  
UPDATE STOKKARTI SET UcuncuBirimMiktari = 1 WHERE ISNULL(UcuncuBirimMiktari,0) = 0 or UcuncuBirimMiktari = ''  
UPDATE STOKKARTI SET DorduncuBirimMiktari = 1 WHERE ISNULL(DorduncuBirimMiktari,0) = 0 or DorduncuBirimMiktari = ''  
UPDATE STOKKARTI SET BesinciBirimMiktari = 1 WHERE ISNULL(BesinciBirimMiktari,0) = 0 or BesinciBirimMiktari = ''  
UPDATE STOKKARTI SET AltinciBirimMiktari = 1 WHERE ISNULL(AltinciBirimMiktari,0) = 0 or AltinciBirimMiktari = ''  
UPDATE Adres SET AdresNo = 10 where AdresNo = 0 
UPDATE a  SET a.AdresNo = tbl.SiraNo from 
	(select CariNo,AdresNo,NoId,RANK () OVER (PARTITION BY CariNo order  BY  AdresNo,NoId) SiraNo from Adres) tbl,Adres a where a.NoId = tbl.NoId
	
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

go--
 if not exists (SELECT 1 FROM VTGuncellemeleri WHERE VTVersiyon='7.1.5')
 	     		  
BEGIN
insert into VTGuncellemeleri (VTVersiyon, SonIslemNo, TarihSaat, Prg)
VALUES ('7.1.5',(select ISLEMNO from ADIGSABITLER ),GETDATE(),'OM')
END
go--


if  not  exists (select * from dbo.syscolumns where id = object_id(N'STOKKARTI') and name=N'StokAdi2')
begin
	ALTER TABLE STOKKARTI ADD StokAdi2 nvarchar(100)
end ELSE BEGIN
	ALTER TABLE STOKKARTI ALTER COLUMN StokAdi2 nvarchar(100)
END
go--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if exists (select * from sys.procedures where name='StokKodAdDegistir')
drop proc StokKodAdDegistir
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
go--

create      procedure StokKodAdDegistir             
@STOKADI nvarchar(500),            
@STOKKODU nvarchar(40),            
@EskiStokKodu nvarchar(40),           
@STOKADI2 nvarchar(100) = ''        
as            
begin Transaction               
 UPDATE STOKHAR SET StokAdi = @STOKADI, StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE MuadilStoklar SET MuadilStokAdi = @STOKADI, MuadilStokKodu= @STOKKODU where MuadilStokKodu= @EskiStokKodu            
 UPDATE StokFiyat SET Kodu= @STOKKODU where Kodu= @EskiStokKodu            
 UPDATE StokDB SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE StokFiyatLog SET Kodu= @STOKKODU where Kodu= @EskiStokKodu            
 UPDATE StokMarkalari SET StokKodu= @STOKKODU where StokKodu=@EskiStokKodu            
 UPDATE Tedarikciler SET StokAdi = @STOKADI, StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE PYazarKasaStoklari SET StokAdi = @STOKADI, StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE PYazarKasaHar SET StokAdi = @STOKADI, StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE PPetrolHar SET StokAdi = @STOKADI, StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE PDegFiyatlar SET StokAdi = @STOKADI, StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE DonemselFiyatListesi SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE TekstilHareketTablosu SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE TekstilHataHareketTablosu SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE TekstilHataliStokVirmanSablonu SET HataliStokKodu= @STOKKODU where HataliStokKodu= @EskiStokKodu            
 UPDATE TekstilHataliStokVirmanSablonu SET VirmanStokKodu= @STOKKODU where VirmanStokKodu= @EskiStokKodu            
 UPDATE TekstilIsEmirleriDetayi SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE TekstilKesimTablosu SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE TekstilStokRenkTanimlari SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE CariUretimFiyatlari SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE Seri SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE Tarim_AmbalajStok SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 UPDATE Tarim_AmbalajStok SET AmbalajKodu= @STOKKODU where AmbalajKodu= @EskiStokKodu            
 UPDATE StokDB SET StokKodu= @STOKKODU where StokKodu= @EskiStokKodu            
 update MH_Connect SET Degeri =@STOKKODU where Degeri=@EskiStokKodu and TabloAdi='STOKKARTI' and FieldAdi='Kodu'            
 Update StokTablolari   Set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu              
 Update Tarim_AmbalajStok  Set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu              
 Update Tarim_AmbalajStok  Set AmbalajKodu=@STOKKODU Where AmbalajKodu=@EskiStokKodu              
 Update Tarim_SatisEmirleri  Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu              
 Update Tarim_UretimDetay  Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu              
 Update Tarim_UretimDetay  Set KasaKodu=@STOKKODU Where KasaKodu=@EskiStokKodu              
 Update Tarim_UretimDetay  Set PaletKodu=@STOKKODU Where PaletKodu=@EskiStokKodu              
 Update Tarim_UretimDetay2  Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu              
 Update Tarim_UrunAlim   Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu              
 Update Tarim_UrunAlimAmbalaj Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu              
 Update Tarim_UrunAlimHareket Set KasaKodu=@STOKKODU Where KasaKodu=@EskiStokKodu              
 Update Tarim_UrunAlimHareket Set PaletKodu=@STOKKODU Where PaletKodu=@EskiStokKodu              
 Update StokTartim    Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu         
 Update StokTartimPalet   Set StokKodu=@STOKKODU, StokAdi=@STOKADI Where StokKodu=@EskiStokKodu             
 Update CariDonemFiyatlari set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu             
 Update ElTerminaliDepoSayim set StokKodu=@STOKKODU, StokAdi=@STOKADI  Where StokKodu=@EskiStokKodu             
 Update ElTerminaliYukleme set StokKodu=@STOKKODU, StokAdi=@STOKADI  Where StokKodu=@EskiStokKodu             
 Update EtiketBarkod set StokKodu=@STOKKODU, StokAdi=@STOKADI  Where StokKodu=@EskiStokKodu             
 Update MiktarsalHedefler set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu             
 Update RenkBedenSeriTablosu set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu             
 Update RenkBedenTablosu set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu             
 Update SIPARISHAR set StokKodu=@STOKKODU, StokAdi=@STOKADI  Where StokKodu=@EskiStokKodu             
 Update TEKLIFHAR set StokKodu=@STOKKODU, StokAdi=@STOKADI  Where StokKodu=@EskiStokKodu               
 Update SeriNoKaliteKontrol set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu             
 Update SipHar set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu           
 Update StokDepoMiktarlari set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu             
 Update StokVergiMuafiyetleri set StokKodu=@STOKKODU Where StokKodu=@EskiStokKodu             
 UPDATE InvoiceItemMap SET OurCode = @STOKKODU,SenderItemName = @STOKADI where OurCode = @EskiStokKodu            
 UPDATE STOKKARTI SET Kodu= @STOKKODU, StokAdi=@STOKADI,StokAdi2 = @STOKADI2 where Kodu= @EskiStokKodu         
 Update StokBarkodlari set StokKodu=@STOKKODU  Where StokKodu=@EskiStokKodu        
 Update StokBarkodlari set Barkodu=@STOKKODU  Where Barkodu=@EskiStokKodu           
          
commit; 

go--

if exists (select * from sys.procedures where name='spStokKartiKaydet')
drop proc spStokKartiKaydet
go--
CREATE     PROCEDURE [dbo].[spStokKartiKaydet]       
 @StokNo int,      
 @Kodu nvarchar(30),      
 @UreticiFirmaKodu nvarchar(30),      
 @StokAdi nvarchar(500),      
 @OzelKod1 nvarchar(8),      
 @OzelKod2 nvarchar(8),      
 @AnaBirim nvarchar(10),      
 @Barkodu nvarchar(40),      
 @IkinciBirim nvarchar(10),      
 @IkinciBirimMiktari float,      
 @IkinciBirimBarkodu nvarchar(40),      
 @UcuncuBirim nvarchar(10),      
 @UcuncuBirimMiktari float,      
 @UcuncuBirimBarkodu nvarchar(40),      
 @DorduncuBirim nvarchar(10),      
 @DorduncuBirimMiktari float,      
 @DorduncuBirimBarkodu nvarchar(40),      
 @AlisKdv smallint,      
 @SatisKdv smallint,      
 @Indirim smallint,      
 @StokAdedi float,      
 @F1Adi nvarchar(10),      
 @F2Adi nvarchar(10),      
 @F3Adi nvarchar(10),      
 @F4Adi nvarchar(10),      
 @F1Fiyat Float,      
 @F2Fiyat Float,      
 @F3Fiyat Float,      
 @F4Fiyat Float,      
 @F1Kdv nvarchar(1),      
 @F2Kdv nvarchar(1),      
 @F3Kdv nvarchar(1),      
 @F4Kdv nvarchar(1),      
 @GrupAdi nvarchar(30),      
 @UrtNo Float,      
 @UrtMiktar Float,      
 @BesinciBirim nvarchar(10),      
 @BesinciBirimMiktari Float,      
 @BesinciBirimBarkodu nvarchar(40),      
 @AltinciBirim nvarchar(10),      
 @AltinciBirimMiktari Float,      
 @AltinciBirimBarkodu nvarchar(40),      
 @AsgariAdet Float,      
 @AzamiAdet Float,      
 @OTVOrani Float,      
 @StokEn Float,      
 @StokBoy Float,      
 @StokYuksekligi Float,      
 @StokKilo Float,      
 @StokRenkKodu nvarchar(15),      
 @KULNO int,      
 @KULADI nvarchar(20),      
 @TP nvarchar(2),      
 @UygFiyat Float,      
 @Aciklama nvarchar(50),      
 @Departman nvarchar(8),      
 @AlisIndirimYuzde Float,      
 @SatisIndirimYuzde Float,      
 @OTVTutari Float,      
 @DepartmanKodu nvarchar(2),      
 @F1DovizKodu nvarchar(2),      
 @F2DovizKodu nvarchar(2),      
 @F3DovizKodu nvarchar(2),      
 @F4DovizKodu nvarchar(2),      
 @Update_Date smalldatetime,      
 @TeraziTusu nvarchar(2),      
 @YKasaTusu nvarchar(2),      
 @Secim nvarchar(10),      
 @AnaStokKodu nvarchar(30),      
 @Ambalaj nvarchar(20),      
 @StokKiloBrut Float,      
 @StokTipi nvarchar(15),      
 @StokOzellikKodu nvarchar(15),      
 @AktifPasif nvarchar(1),      
 @OzelBarkod Float,      
 @Olcu nvarchar(8),      
 @AlisIndirimYuzde2 Float,      
 @AlisIndirimYuzde3 Float,      
 @AlisIndirimYuzde4 Float,      
 @SatisIndirimYuzde2 Float,      
 @SatisIndirimYuzde3 Float,      
 @SatisIndirimYuzde4 Float,      
 @MuadilStokNo int,      
 @BonusPuani Float,      
 @BonusPuaniSatici Float,      
 @OlmasiGerekenAdet float,      
 @PrimYuzde float,      
  @StokBedenNo nvarchar(15),      
 @StokRenkBedenCalisir nvarchar(1),      
 @WASG nvarchar(1),      
 @WebGrupAdi nvarchar(30),      
 @SKFIK int,      
 @GrupOzelKod1 nvarchar(15),      
 @GrupOzelKod2 nvarchar(15),      
 @GrupOzelKod3 nvarchar(15),      
 @GrupOzelKod4 nvarchar(15),      
  @OrjinalKodu nvarchar(30),      
 @StokAdi2 nvarchar(100),      
 @Aciklama2 nvarchar(400),      
 @WebGrupAdi2 nvarchar(30),      
 @StokAgirlik Float,      
 @StokMaxAgirlik Float,      
 @StokMinAgirlik Float,      
   @AltGrupAdi nvarchar(30),      
 @AltGrupAdi2 nvarchar(30),      
 @SeriNoTakibi bit,      
 @IRKI nvarchar(30),      
 @SuniTohum bit,       
 @OzelKod3 nvarchar(8),        
 @OzelKod4 nvarchar(8),      
 @Icmal bit,      
 @SatisFiyatiDegistirilemez bit,      
 @A_Muh_Kodu nvarchar(20),      
 @S_Muh_Kodu nvarchar(20),      
 @FireOrani float,      
 @WebdeGosterilsinmi bit,      
 @TarimElTerminliGosterilsinmi bit,      
 @AltGrupAdi3 nvarchar(30),      
 @AdetTakibi bit,      
 @LotTakibi bit,    
 @UlkeKodu nvarchar(3)  
   
AS       
INSERT STOKKARTI  (StokNo,      
  Kodu,      
  UreticiFirmaKodu,      
  StokAdi,      
  OzelKod1,      
  OzelKod2,      
  AnaBirim,      
  Barkodu,      
  IkinciBirim,      
  IkinciBirimMiktari,      
  IkinciBirimBarkodu,      
  UcuncuBirim,      
  UcuncuBirimMiktari,      
  UcuncuBirimBarkodu,      
  DorduncuBirim,      
  DorduncuBirimMiktari,      
  DorduncuBirimBarkodu,      
  AlisKdv,      
  SatisKdv,      
  Indirim,      
  StokAdedi,      
  F1Adi,      
  F2Adi,      
  F3Adi,      
  F4Adi,      
  F1Fiyat,      
  F2Fiyat,      
  F3Fiyat,      
  F4Fiyat,      
  F1Kdv,      
  F2Kdv,      
  F3Kdv,      
  F4Kdv,      
  GrupAdi,      
  UrtNo,      
  UrtMiktar,      
  BesinciBirim,      
  BesinciBirimMiktari,      
  BesinciBirimBarkodu,      
  AltinciBirim,      
  AltinciBirimMiktari,      
  AltinciBirimBarkodu,      
  AsgariAdet,      
  AzamiAdet,      
  OTVOrani,      
  StokEn,      
  StokBoy,      
  StokYuksekligi,      
  StokKilo,      
  StokRenkKodu,      
  KULNO,      
  KULADI,      
  TP,      
  UygFiyat,      
  Aciklama,      
  Departman,      
  AlisIndirimYuzde,      
  SatisIndirimYuzde,      
  OTVTutari,      
  DepartmanKodu,      
  F1DovizKodu,      
  F2DovizKodu,      
  F3DovizKodu,      
  F4DovizKodu,      
  Update_Date,      
  TeraziTusu,      
  YKasaTusu,      
  Secim,      
  AnaStokKodu,      
  Ambalaj,      
  StokKiloBrut,      
  StokTipi,      
  StokOzellikKodu,      
  AktifPasif,      
  OzelBarkod,      
  Olcu,      
  AlisIndirimYuzde2,      
  AlisIndirimYuzde3,      
  AlisIndirimYuzde4,      
  SatisIndirimYuzde2,      
  SatisIndirimYuzde3,      
  SatisIndirimYuzde4,      
  MuadilStokNo,      
  BonusPuani,      
  BonusPuaniSatici,      
  OlmasiGerekenAdet,      
  PrimYuzde,      
   StokBedenNo,      
  StokRenkBedenCalisir,      
  WASG,      
  WebGrupAdi,      
  SKFIK,      
  GrupOzelKod1,      
  GrupOzelKod2,      
  GrupOzelKod3,      
  GrupOzelKod4,      
   OrjinalKodu,      
  StokAdi2,      
  Aciklama2,      
  WebGrupAdi2,      
  StokAgirlik,      
  StokMaxAgirlik,      
  StokMinAgirlik,      
  AltGrupAdi,      
  AltGrupAdi2,      
  SeriNoTakibi,      
  IRKI,      
  SuniTohum,      
  OzelKod3,      
  OzelKod4,      
  Icmal,      
  SatisFiyatiDegistirilemez,      
  A_Muh_Kodu,      
  S_Muh_Kodu,      
  FireOrani,      
  WebdeGosterilsinmi,      
  TarimElTerminliGosterilsinmi,      
  AltGrupAdi3,      
  AdetTakibi,      
 LotTakibi,    
 UlkeKodu )    
  
  
  
VALUES (@StokNo,      
 @Kodu,      
 @UreticiFirmaKodu,      
 @StokAdi,      
 @OzelKod1,      
 @OzelKod2,      
 @AnaBirim,      
 @Barkodu,      
 @IkinciBirim,      
 @IkinciBirimMiktari,      
 @IkinciBirimBarkodu,      
 @UcuncuBirim,      
 @UcuncuBirimMiktari,      
 @UcuncuBirimBarkodu,      
 @DorduncuBirim,      
 @DorduncuBirimMiktari,      
 @DorduncuBirimBarkodu,      
 @AlisKdv,      
 @SatisKdv,      
 @Indirim,      
 @StokAdedi,      
 @F1Adi,      
 @F2Adi,      
 @F3Adi,      
 @F4Adi,      
 @F1Fiyat,      
 @F2Fiyat,      
 @F3Fiyat,      
 @F4Fiyat,      
 @F1Kdv,      
 @F2Kdv,      
 @F3Kdv,      
 @F4Kdv,      
 @GrupAdi,      
 @UrtNo,      
 @UrtMiktar,      
 @BesinciBirim,      
 @BesinciBirimMiktari,      
 @BesinciBirimBarkodu,      
 @AltinciBirim,      
 @AltinciBirimMiktari,      
 @AltinciBirimBarkodu,      
 @AsgariAdet,      
 @AzamiAdet,      
 @OTVOrani,      
 @StokEn,      
 @StokBoy,      
 @StokYuksekligi,      
 @StokKilo,      
 @StokRenkKodu,      
 @KULNO,      
 @KULADI,      
 @TP,      
 @UygFiyat,      
 @Aciklama,      
 @Departman,      
 @AlisIndirimYuzde,      
 @SatisIndirimYuzde,      
 @OTVTutari,      
 @DepartmanKodu,      
 @F1DovizKodu,      
 @F2DovizKodu,      
 @F3DovizKodu,      
 @F4DovizKodu,      
 @Update_Date,      
 @TeraziTusu,      
 @YKasaTusu,      
 @Secim,      
 @AnaStokKodu,      
 @Ambalaj,      
 @StokKiloBrut,      
 @StokTipi,      
 @StokOzellikKodu,      
 @AktifPasif,      
 @OzelBarkod,      
 @Olcu,      
 @AlisIndirimYuzde2,      
 @AlisIndirimYuzde3,      
 @AlisIndirimYuzde4,      
 @SatisIndirimYuzde2,      
 @SatisIndirimYuzde3,      
 @SatisIndirimYuzde4,      
 @MuadilStokNo,      
 @BonusPuani,      
 @BonusPuaniSatici,      
 @OlmasiGerekenAdet,      
 @PrimYuzde,      
  @StokBedenNo,      
 @StokRenkBedenCalisir,      
 @WASG,      
 @WebGrupAdi,      
 @SKFIK,      
 @GrupOzelKod1,      
 @GrupOzelKod2,      
 @GrupOzelKod3,      
 @GrupOzelKod4,      
  @OrjinalKodu,      
 @StokAdi2,      
 @Aciklama2,      
 @WebGrupAdi2,      
 @StokAgirlik,      
 @StokMaxAgirlik,      
 @StokMinAgirlik,      
 @AltGrupAdi,      
 @AltGrupAdi2,      
 @SeriNoTakibi,      
 @IRKI,      
 @SuniTohum,      
 @OzelKod3,      
 @OzelKod4,      
 @Icmal,      
 @SatisFiyatiDegistirilemez,      
 @A_Muh_Kodu,      
 @S_Muh_Kodu,      
 @FireOrani,      
 @WebdeGosterilsinmi,      
 @TarimElTerminliGosterilsinmi,      
 @AltGrupAdi3,      
 @AdetTakibi,      
@LotTakibi,    
@UlkeKodu)  


go--
if  (select  count(*) from  STOKKARTI where StokNo is null) = 0 and not exists (select  count(*) from  STOKKARTI GROUP BY StokNo HAVING count(*) > 1)
begin
	update ADIGSABITLER SET STOKNO =ISNULL((SELECT MAX(StokNo) from STOKKARTI ),1)+1
end;
go--
DELETE FROM GridView where KayitIsmi  = 'frmOncekiveSonrakiOdemePlanlaricxGridtvSorgu' and GirdAdi  ='Genel Rapor Gridi'
go--
if  not  exists (select * from dbo.syscolumns where id = object_id(N'StokVergiMuafiyetleri') and name=N'StokKodu')
begin
	ALTER TABLE StokVergiMuafiyetleri ADD StokKodu nvarchar(30)
end ELSE BEGIN
	ALTER TABLE StokVergiMuafiyetleri ALTER COLUMN StokKodu nvarchar(30)
END
go--
if exists (select * from sys.procedures where name='spStkDINAMIKInvoiceIhracat')
drop proc spStkDINAMIKInvoiceIhracat
go--

CREATE   proc [dbo].[spStkDINAMIKInvoiceIhracat] @Tarih1 datetime ,@Tarih2 datetime  
as  
select (K.StokAdi + '-- '  + K.StokAdi2 ) AS STOKADI , H.Birim , H.Miktar , (H.BirimFiyat/H.DovizKuru) DovizBirimFiyatı,H.DovizKodu,(H.BirimFiyat/H.DovizKuru*H.Miktar)  
TOPLAM ,H.DovizKodu,  
H.IslemNo,H.IslemNo3,K.Aciklama2  
from STOKHAR H LEFT JOIN STOKKARTI K ON H.StokKodu=K.Kodu  
where H.FaturaTarihi>=@Tarih1 and H.FaturaTarihi <=@Tarih2  
ORDER BY H.IslemNo3,H.IslemNo,H.NoId

go--
if exists (select * from sys.procedures where name='spTahsilVadeRaporuCari')
drop proc spTahsilVadeRaporuCari
 go--
-------------------------------------------------------------------------------------------------------------------------------------------

create    proc [dbo].[spTahsilVadeRaporuCari] (@CariNo int = 0)        
as   

create table #odeme          
(          
  RecID integer Identity (1, 1) not null, NoId integer, IslemNo integer, Tarih datetime,          
  CariNo integer,  IslemTuru nvarchar(20) COLLATE DATABASE_DEFAULT,  Bakiye float,  Borc_Kullanilan float ,  Devreden float,  Borc float,          
  Devir float  PRIMARY KEY CLUSTERED  (RecID)          
)          
        
Declare @DagitimTutari float          
Declare @NoId integer,  @IslemNo integer,  @Tarih datetime,  @Borc decimal (28, 14), @Borc_Kullanilan decimal (28, 14),  @Son_Kalan_Tutar float,  @IslemTuru nvarchar(20), @TmpTutar decimal(28, 14)               
    
IF @CariNo = 0       
 declare cr_cari cursor  FAST_FORWARD READ_ONLY  for Select MUSNO from V_AMUSTERI where MUSDURUM='A' and MUSBAKIYE > 0.01      
ELSE       
 declare cr_cari cursor  FAST_FORWARD READ_ONLY  for Select MUSNO from V_AMUSTERI where MUSDURUM='A' and MUSBAKIYE > 0.01 and MUSNO = @CariNo      
    
open cr_cari          
fetch next from cr_cari       
into @CariNo      
      
while (@@FETCH_STATUS = 0)    
begin    
  set @DagitimTutari = (select SUM (BORC-ALACAK) from ACARI WHERE MUSNO=@CariNo)           
  set @TmpTutar = @DagitimTutari        
  declare cr_Prepare cursor FAST_FORWARD READ_ONLY for          
  select             
    odm.NoId,          
    odm.IslemNo,          
    odm.Tarih,          
    odm.CariNo,          
    odm.Borc,          
    odm.BAAcikla          
  from Odeme odm          
  where          
  odm.CariNo = @CariNo and          
  IsNull (odm.Borc, 0) > 0          
  order by          
    odm.Tarih desc,NoId desc          
          
  open cr_Prepare          
  fetch next from cr_Prepare          
  into          
    @NoId,          
    @IslemNo,          
    @Tarih,          
    @CariNo,          
    @Borc,          
    @IslemTuru          
          
  while (@@FETCH_STATUS = 0) and (@TmpTutar > 0.0)          
  begin      
    if @Borc >= @TmpTutar           
    begin          
   set @Borc_Kullanilan = @TmpTutar          
   set @Son_Kalan_Tutar = @TmpTutar - @Borc          
   set @TmpTutar = 0.0          
    end          
    else          
    begin          
   set @TmpTutar = @TmpTutar - @Borc          
   set @Borc_Kullanilan = @Borc          
   set @Son_Kalan_Tutar = @TmpTutar          
    end          
          
    insert into #odeme           
    (          
   NoId,          
   IslemNo,          
   Tarih,          
   CariNo,          
   Borc,          
   Borc_Kullanilan,          
   Devreden,          
   Bakiye,          
   Devir,          
   IslemTuru          
    )          
    values          
    (          
   @NoId,           
   @IslemNo,          
   @Tarih,          
   @CariNo,          
   @Borc,          
   @Borc_Kullanilan,          
   @Son_Kalan_Tutar,          
   @DagitimTutari,          
   @Son_Kalan_Tutar+@Borc,          
   @IslemTuru          
    )          
          
    fetch next from cr_Prepare          
    into          
   @NoId,          
   @IslemNo,          
   @Tarih,          
   @CariNo,          
   @Borc,          
   @IslemTuru          
  end             
  close cr_Prepare          
  deallocate cr_Prepare           
      
  update #odeme SET Borc = Devir where RecID = @@IDENTITY      
    
FETCH NEXT FROM cr_Cari INTO @CariNo    
end    
close cr_Cari         
deallocate cr_Cari          
    
declare @paramkolon nvarchar(max),@paramkolonsorgu nvarchar(max)  
declare @Type nvarchar(2),@Id int,@Gun1 int,@Gun2 int, @KolonAdi nvarchar(25)  
declare @kolonsira int,@par_cnt int,@bk_isaret nvarchar(1)  
  
select @par_cnt = count(*) from BakiyeKapatmaParametre  
  
set @kolonsira = 0  
set @paramkolon = '';  
set @paramkolonsorgu = '';  
declare cr_Parametre cursor  FAST_FORWARD READ_ONLY  for   
select 'GO' Tur,NoId,Gun1,Gun2,'GO'+KolonAdi KolonAdi from BakiyeKapatmaParametre   
union all   
select 'EO',NoId,Gun1*-1,Gun2*-1,'EO'+KolonAdi KolonAdi from BakiyeKapatmaParametre   order by Tur desc,NoId   
   
open cr_Parametre 
fetch next from cr_Parametre        			 
into @Type,@Id,@Gun1,@Gun2,@KolonAdi   
 while (@@FETCH_STATUS = 0)         
 begin    
  if @kolonsira = 0   
  begin   
   if @Type = 'GO'  
   begin  
    SET @paramkolon = '['+@KolonAdi+']';  
    SET @paramkolonsorgu = 'CASE WHEN [Geciken Gün]  >= ' +CAST(@Gun1 as nvarchar(5))+ ' and [Geciken Gün] <='+CAST(@Gun2 as nvarchar(5))+' THEN  '''+@KolonAdi+'''';    
   end  
   else  
   begin  
    SET @paramkolon = '['+@KolonAdi+']';  
    SET @paramkolonsorgu = 'CASE WHEN [Geciken Gün]  <= ' +CAST(@Gun1 as nvarchar(5))+ ' and [Geciken Gün] >='+CAST(@Gun2 as nvarchar(5))+' THEN  '''+@KolonAdi+'''';  
   end;  
  end  
  else  
  begin  
   if @Type = 'GO'  
   begin  
    SET @paramkolon = @paramkolon + ',['+@KolonAdi+']'  
    IF @Id = @par_cnt  
     SET @paramkolonsorgu = @paramkolonsorgu + ' WHEN [Geciken Gün]  > ' +CAST(@Gun1 as nvarchar(5))+ ' THEN  '''+@KolonAdi+'''';;   
    ELSE  
     SET @paramkolonsorgu = @paramkolonsorgu + ' WHEN [Geciken Gün]  > ' +CAST(@Gun1 as nvarchar(5))+ ' and [Geciken Gün] <='+CAST(@Gun2 as nvarchar(5))+' THEN  '''+@KolonAdi+'''';   
   end  
   else  
   begin  
    SET @paramkolon = @paramkolon + ',['+@KolonAdi+']'  
    IF @Id = @par_cnt  
     SET @paramkolonsorgu = @paramkolonsorgu + ' WHEN [Geciken Gün]  < ' +CAST(@Gun1 as nvarchar(5))+ ' THEN  '''+@KolonAdi+'''';  
    ELSE  
     SET @paramkolonsorgu = @paramkolonsorgu + ' WHEN [Geciken Gün]  < ' +CAST(@Gun1 as nvarchar(5))+ ' and [Geciken Gün] >='+CAST(@Gun2 as nvarchar(5))+' THEN  '''+@KolonAdi+'''';  
   end;  
  end;       
  SET @kolonsira = @kolonsira + 1;  
 FETCH NEXT FROM cr_Parametre INTO @Type,@Id,@Gun1,@Gun2,@KolonAdi     
 end  
close cr_Parametre         
deallocate cr_Parametre     
SET @paramkolonsorgu = @paramkolonsorgu + ' END GUN'  
  
declare @sorgu nvarchar(max);  
SET @sorgu = '   
Select * from (      
Select     
 [Cari No],    
 [Cari Kodu],    
 [Cari Adı],    
    [Özelkod 1],    
    [Özelkod 2] ,    
    [Özelkod 3],    
    [Özelkod 4],    
    [Telefon],    
    [Cep Telefon],    
    [İl],    
    [İlçe],    
    [Tipi],    
    [Departman],    
    [Satıcı Kodu],    
    [Satıcı Adı],    
    Kilitli,     
 ROUND([Cari Bakiye],0) [Cari Bakiye],ROUND(Borç,0) Borç,      
    '+@paramkolonsorgu+'  
from (        
select          
  RecID,        
  o.NoId,        
  a.MUSNO  [Cari No],          
  a.MUSKOD [Cari Kodu],          
  a.MUSADI [Cari Adı],          
  a.MUSBAKIYE [Cari Bakiye],      
  o.IslemTuru [İşlem Türü],          
  o.IslemNo [İşlem No],          
  c.ACIKLAMA [Açıklama],          
  CONVERT(nvarchar(10),c.TARIH,104)  [İşlem Tarihi],          
  CONVERT(nvarchar(10),o.Tarih,104)  [Vade Tarihi],        
  o.Tarih orderbytarih,      
  CAST(GETDATE() - o.Tarih as int) [Geciken Gün],        
  CASE WHEN CAST(GETDATE() - o.Tarih as int) >=  0 THEN ''GO'' ELSE ''EO'' END Tip,      
  Devreden,        
  o.Borc [Borç],          
  o.Devir,          
  o.Bakiye,          
  a.OZELKOD1 [Özelkod 1],    
  a.OZELKOD2 [Özelkod 2] ,    
  a.OZELKOD3 [Özelkod 3],    
  a.OZELKOD4 [Özelkod 4],    
  a.MUSTEL [Telefon],    
  a.MUSCEP [Cep Telefon],    
  a.MUSIL [İl],    
  a.MUSILCE [İlçe],    
  a.Tipi [Tipi],    
  a.Departman [Departman],    
  a.SaticiKodu [Satıcı Kodu],    
  a.SaticiAdi [Satıcı Adı],    
  a.Kilitli     
 from #odeme o          
 left join  V_AMUSTERI a on  o.CariNo = a.MUSNO          
 left join  ACARI    c on c.ISLEMNO = o.IslemNo and c.BAACIKLA = o.IslemTuru and c.BORC=o.Borc       
 ) t      
 )table1      
 PIVOT        
(        
  SUM([Borç])        
  FOR GUN IN ('+@paramkolon+')        
) AS PivotTable';        
--print @sorgu  
 EXEC sp_executesql @sorgu; 
go--

 if not exists (SELECT 1 FROM VTGuncellemeleri WHERE VTVersiyon='7.1.7')
BEGIN
insert into VTGuncellemeleri (VTVersiyon, SonIslemNo, TarihSaat, Prg)
VALUES ('7.1.7',(select ISLEMNO from ADIGSABITLER ),GETDATE(),'OM')
END
     			
go--

select top 5 * from VTGuncellemeleri order by VTVersiyon desc

go--
if exists (select * from sys.procedures where name='sp_FaturaIslemleriListesi')
drop proc sp_FaturaIslemleriListesi
go--
CREATE   PROCEDURE [dbo].[sp_FaturaIslemleriListesi]                                          
  @tarih1 varchar(20),                                           
  @tarih2 varchar(20),                                          
  @dep varchar(500),                                          
  @orderby int,                                          
  @arama varchar(100),                                          
  @GosterilecekKayit int,                                          
  @IslemTuru varchar(20),                                          
  @Durumu int,                              
  @IslemTipi  varchar(30),                  
  @FatSerNo  varchar(3),                  
  @eFaturaNo  varchar(30),                  
  @FaturaTuru varchar(1),      
  @IslemNoLike bit = 0        
AS                                          
              
declare @str nvarchar(max)                                          
declare @rc int                                           
declare @tmp table (trc int)                                          
declare @ayrac varchar(2)                  
declare @peFaturaNo varchar(50)          
if @eFaturaNo<>''          
select @peFaturaNo=UPPER(@eFaturaNo)          
else set @peFaturaNo=''          
set @ayrac='"';                  
            
set @str='select count(*) from (select IslemNo from STOKHARDETBAG where FisTuru = ''F'' AND FaturaTarihi >='''+ @Tarih1+                        
''' and FaturaTarihi <= '''+@Tarih2+'''';       
  
if @peFaturaNo<>''                  
set @str=@str+'and upper(eFaturaNo) like upper(''%'+@peFaturaNo+'%'') '     
  
if @FatSerNo<>''                  
set @str=@str+'and Replace(FatSerNo,'''''''','''+@ayrac+''') = '''+@FatSerNo+''' '    
                                     
if @dep <> ''                                          
 set @str=@str+' and Departman in ('+@Dep+')'                                          
if @IslemTuru <> 'Tümü'                                          
 set @str=@str+' and IslemTuru = '''+@IslemTuru+''''                                
if @IslemTipi <> 'Tümü' and   @IslemTipi <> ''                                         
 set @str=@str+' and IslemTipi like ''%'+@IslemTipi+'%'''                                
      
if @arama <> ''       
begin      
if @orderby=0       
begin      
 if @IslemNoLike = 0      
 set @str=@str+'and CAST(IslemNo as nvarchar(20)) = '''+@arama+''' '       
 else      
 set @str=@str+'and IslemNo like ''%'+@arama+'%'' '       
end;                                        
if @orderby=1                                           
 set @str=@str+'and upper(FaturaNo) like upper('''+@arama+'%'') '                                           
if @orderby=2                                           
 set @str=@str+'and upper(CariAdi) like upper(''%'+@arama+'%'') '                                          
if @orderby=3                                           
 set @str=@str+'and upper(CariKodu) like upper('''+@arama+'%'') '                                           
if @orderby=4                                          
 set @str=@str+'and upper(KULADI) like upper(''%'+@arama+'%'') '                                          
if @orderby=5                                          
 set @str=@str+'and upper(SaticiAdi) like upper(''%'+@arama+'%'') '                               
 if @orderby=6                                          
 set @str=@str+'and upper(eFaturaDurumu) like upper(''%'+@arama+'%'') '                               
if @orderby=7                                          
 set @str=@str+'and upper(YaziciCount) like upper(''%'+@arama+'%'') '                               
if @orderby=8                                          
 set @str=@str+'and upper(FaturaTarihi) like upper(''%'+@arama+'%'') '             
if @orderby=9                                          
 set @str=@str+'and ((upper(Ack1) like upper(''%'+@arama+'%'')) or (upper(Ack2) like upper(''%'+@arama+'%'')) or (upper(Ack3) like upper(''%'+@arama+'%'')) or (upper(Ack4) like upper(''%'+@arama+'%''))     
   or EXISTS (Select 1 from ACARI AC where AC.ISLEMNO = IslemNo and upper(Aciklama2) like upper(''%'+@arama+'%''))    
      or EXISTS (Select 1 from ACIKLAMA AC where AC.FATURANO = IslemNo and upper(TeslimEden) like upper(''%'+@arama+'%''))    
      or EXISTS (Select 1 from ACIKLAMA AC where AC.FATURANO = IslemNo and upper(TeslimAlan) like upper(''%'+@arama+'%''))) '       
end;                                      
set @str=@str+')Y';                                                            
    
insert @tmp exec(@str)                                          
select @rc = trc from @tmp;                 
                  
declare @tstr varchar(100);                                        
                                        
if @orderby in (0,9)                                          
  set @tstr='IslemNo'                                          
if @orderby=1                                           
 set @tstr='FaturaNo'                                           
if @orderby=2                                           
 set @tstr='CariAdi'                                          
if @orderby=3                                           
 set @tstr='CariKodu'                                           
if @orderby=4                                          
 set @tstr='KULADI'                                          
if @orderby=5                                          
 set @tstr='SaticiAdi'                                
if @orderby=6                                          
 set @tstr='eFaturaDurumu'                   
 if @orderby=7                                          
 set @tstr='YaziciCount'                   
 if @orderby=8                                          
 set @tstr='FaturaTarihi'                   
                   
set @str='select '''' as plaka, *, '+                      
   'CASE YazarKasaFisNo when 0 then ''TICARIFATURA'' '+                      
   'when 1 then ''TEMELFATURA'' '+                      
   'when 2 then ''IHRACAT'' else ''TICARIFATURA'' end + '' / ''+ case FaturaTipi  when 0 then ''SATIS'' when 1 then ''TEVKIFAT'' when 2 then ''IADE'' when 3 then ''IHRACKAYITLI'' when 4 then ''ISTISNA'' '+                       
   'when 5 then ''MOBIL'' else ''SATIS'' end FaturaSenaryoTip '+                      
   'from STOKHARDETBAG '+                                          
   'where IslemNo in (select X.IslemNo '+                                          
   'from (select ROW_NUMBER() over (order by '+@tstr+') as sira, IslemNo '+                                          
   'from STOKHARDETBAG where FisTuru = '''+@FaturaTuru+''' and FaturaTarihi >='''+@Tarih1+''' and FaturaTarihi <= '''+@Tarih2+'''';                                          
if @peFaturaNo<>''                  
set @str=@str+'and upper(eFaturaNo) like upper(''%'+@peFaturaNo+'%'') '                  
                  
if @FatSerNo<>''                  
set @str=@str+'and Replace(FatSerNo,'''''''','''+@ayrac+''') = '''+@FatSerNo+''' '                  
                  
if @dep <> ''                                          
 set @str=@str+' and Departman in ('+@Dep+')'                                          
if @IslemTuru <> 'Tümü'                                          
 set @str=@str+' and IslemTuru = '''+@IslemTuru+''''                                  
if @IslemTipi <> 'Tümü' and @IslemTipi <> ''                                          
 set @str=@str+' and IslemTipi = '''+@IslemTipi+''''                             
      
if @arama <> ''       
begin                       
if @orderby=0       
begin      
 if @IslemNoLike = 0      
 set @str=@str+'and CAST(IslemNo as nvarchar(20)) = '''+@arama+''' '       
 else      
 set @str=@str+'and IslemNo like ''%'+@arama+'%'' '       
end;                                          
if @orderby=1                                           
 set @str=@str+'and upper(FaturaNo) like upper('''+@arama+'%'') '                                           
if @orderby=2                                           
 set @str=@str+'and upper(CariAdi) like upper(''%'+@arama+'%'') '                                          
if @orderby=3                                           
 set @str=@str+'and upper(CariKodu) like upper('''+@arama+'%'') '                                           
if @orderby=4                                          
 set @str=@str+'and upper(KULADI) like upper(''%'+@arama+'%'') '                                          
if @orderby=5       
 set @str=@str+'and upper(SaticiAdi) like upper(''%'+@arama+'%'') '                               
 if @orderby=6                                          
 set @str=@str+'and upper(eFaturaDurumu) like upper(''%'+@arama+'%'') '                               
if @orderby=7                                          
 set @str=@str+'and upper(YaziciCount) like upper(''%'+@arama+'%'') '                               
if @orderby=8                                          
 set @str=@str+'and upper(FaturaTarihi) like upper(''%'+@arama+'%'') '    
if @orderby=9                                          
 set @str=@str+'and ((upper(Ack1) like upper(''%'+@arama+'%'')) or (upper(Ack2) like upper(''%'+@arama+'%'')) or (upper(Ack3) like upper(''%'+@arama+'%'')) or (upper(Ack4) like upper(''%'+@arama+'%''))     
      or EXISTS (Select 1 from ACARI AC where AC.ISLEMNO = IslemNo and upper(Aciklama2) like upper(''%'+@arama+'%''))    
      or EXISTS (Select 1 from ACIKLAMA AC where AC.FATURANO = IslemNo and upper(TeslimEden) like upper(''%'+@arama+'%''))    
      or EXISTS (Select 1 from ACIKLAMA AC where AC.FATURANO = IslemNo and upper(TeslimAlan) like upper(''%'+@arama+'%''))) '        
end;                              
                     
set @str=@str+')X where X.sira >'+convert(varchar,@rc - @GosterilecekKayit) +') order by ';                                          
                                          
if @orderby in (0,9)                                          
  set @str=@str+'IslemNo'                      
if @orderby=1                                           
 set @str=@str+'FaturaNo'                                           
if @orderby=2                                           
 set @str=@str+'CariAdi'                                          
if @orderby=3                                           
 set @str=@str+'CariKodu'                            
if @orderby=4                                          
 set @str=@str+'KULADI'                                          
if @orderby=5                                          
 set @str=@str+'SaticiAdi'                                          
if @orderby=6                                          
 set @str=@str+'eFaturaDurumu'                     
if @orderby=7                                       
 set @str=@str+'YaziciCount'                     
if @orderby=8                                          
 set @str=@str+'FaturaTarihi'                          
exec(@str)   
go--
alter table AMUSTERI alter column MUSIL varchar(100) null
alter table AMUSTERI alter column MUSILCE varchar(100) null
go--
if exists (select * from sys.procedures where name='sp_GELGIDH')
drop proc [sp_GELGIDH]
go--

CREATE  PROC [dbo].[sp_GELGIDH]   
(@tarih1 varchar(20),  
@tarih2 varchar(20),   
@dep varchar(500),   
@orderby int,   
@arama varchar(100),  
@GosterilecekKayit int,  
@IslemTuru varchar(5),  
@KarsiHesap varchar(50),  
@IslemNoLike bit = 0,
@KarsiHesapAdi varchar(150)
)  
as        
begin     
declare @l_KarsiHesapAdi nvarchar(150)
SET @l_KarsiHesapAdi = UPPER(@KarsiHesapAdi)
declare @str varchar(max)              
        
set @str='select * from (select TOP ' + CAST(@GosterilecekKayit as nvarchar(10)) + ' * from GELGID where TARIH >='''+ @Tarih1+''' and TARIH <= '''+@Tarih2+'''';        
        
if @dep <> ''        
 set @str=@str+' and Departman in ('+@Dep+')'        
if @IslemTuru <> 'Tümü'        
 set @str=@str+' and BAACIKLA = '''+@IslemTuru+''''        
if @KarsiHesap <> 'Tümü'        
 set @str=@str+' and KarsiHesp = '''+@KarsiHesap+''''      
   
if @KarsiHesapAdi <> ''        
 set @str=@str+' and (UPPER(HesapAdi) like ''%'+@l_KarsiHesapAdi+'%'' or UPPER(KASAADI) like ''%'+@l_KarsiHesapAdi+'%'' or UPPER(MUSADI) like ''%'+@l_KarsiHesapAdi+'%'')'
 
if @arama <> ''   
begin        
if @orderby=0   
begin  
  if @IslemNoLike = 0  
  set @str=@str+'and CAST(ISLEMNO as nvarchar(20)) = '''+@arama+''' '   
  else  
  set @str=@str+'and ISLEMNO like ''%'+@arama+'%'' '   
 end;  
  
 if @orderby=1         
  set @str=@str+'and upper(GELGIDKODU) like upper('''+@arama+'%'') '         
 if @orderby=2         
  set @str=@str+'and upper(GELGIDADI) like upper(''%'+@arama+'%'') '        
 if @orderby=3         
  set @str=@str+'and upper(ACIKLAMA) like upper(''%'+@arama+'%'') '         
 
end;  
  
set @str=@str+' ORDER BY ISLEMNO DESC) y order by ISLEMNO';            
EXEC    (@str)       
PRINT (@str)        
end;  

go--
IF  EXISTS (SELECT *  FROM sys.views WHERE  name='V_Odeme')
 BEGIN 
 drop view V_Odeme
 end
go--
CREATE  VIEW [dbo].[V_Odeme] 
AS 
SELECT     dbo.Odeme.NoId, dbo.Odeme.IslemNo, dbo.Odeme.Tarih, dbo.Odeme.Tutar, dbo.Odeme.Aciklama, dbo.Odeme.Durum, dbo.Odeme.CariNo, dbo.Odeme.CariKodu, 
           dbo.ACARI.MUSADI, dbo.Odeme.Borc, dbo.Odeme.Alacak, dbo.Odeme.NoNo, dbo.Odeme.KULNO, 
                      dbo.Odeme.BAAcikla, dbo.Odeme.Departman, dbo.Odeme.KayitDuzeyi, dbo.Odeme.SiraNo, dbo.Odeme.Modul, ISNULL(dbo.ACARI.DOVIZCINSI, 1) 
                      AS DOVIZCINSI, ISNULL(dbo.ACARI.DOVIZKODU, 'YP') AS DOVIZKODU, 
                      dbo.ACARI.DovizKur
FROM         dbo.ACARI  --RIGHT OUTER JOIN
             INNER JOIN  dbo.Odeme ON dbo.ACARI.BAACIKLA = dbo.Odeme.BAAcikla AND dbo.ACARI.MUSNO = dbo.Odeme.CariNo AND dbo.ACARI.ISLEMNO = dbo.Odeme.IslemNo
go--
IF  EXISTS (SELECT *  FROM sys.views WHERE  name='V_Odeme_DvzBA')
 BEGIN 
 drop view V_Odeme_DvzBA
 end
go--

CREATE  VIEW [dbo].[V_Odeme_DvzBA] 
AS 
SELECT     NoId, IslemNo, Tarih, Tutar, Aciklama, Durum, CariNo, CariKodu, Borc, Alacak, NoNo, KULNO, BAAcikla, Departman, 
                      KayitDuzeyi, SiraNo, Modul, DOVIZCINSI, DOVIZKODU, DovizKur,
                      CASE WHEN Borc = 0 THEN 0 ELSE Borc / DovizKur END AS DovizBorc, CASE WHEN Alacak = 0 THEN 0 ELSE Alacak / DovizKur
                      END AS DovizAlacak
FROM         dbo.V_Odeme

go--
delete from GridView where GirdAdi in ('Günlük Durum Raporu Gridi','Fatura İşlemleri İşlem Gridi')
go--
INSERT INTO VergiMuafiyetleri (Kod,Aciklama) 
Select '0','YOK'  WHERE NOT EXISTS (select 1 from VergiMuafiyetleri where Kod = '0')

go--

IF (Select COUNT(*) from Parametre where Param = 'Vergi Muafiyet Kodu')  = 0  
BEGIN
	Insert into Parametre Select'Vergi Muafiyet Kodu','0'
END
ELSE IF  (Select COUNT(*) from Parametre where Param = 'Vergi Muafiyet Kodu' and (Deger = '' or Deger is null))  > 0  
BEGIN
	update Parametre SET Deger = '0' where Param = 'Vergi Muafiyet Kodu'	
END;
go--
        
go--
if not exists (SELECT 1 FROM VTGuncellemeleri WHERE VTVersiyon='7.1.8')
BEGIN
insert into VTGuncellemeleri (VTVersiyon, SonIslemNo, TarihSaat, Prg)
VALUES ('7.1.8',(select ISLEMNO from ADIGSABITLER ),GETDATE(),'OM')
END
go--
if  not  exists (select * from dbo.syscolumns where id = object_id(N'DOVIZT') and name=N'HPS_Gorunsun')
begin
ALTER TABLE DOVIZT ADD HPS_Gorunsun bit default 1
end
go--
--------------------------------------------------------------
update KullaniciAyarlari set Deger='YOK'  where Ayar  ='Kullanılacak Modem Adı' AND Deger='Default'
go--
----------------------------------------------------------------

INSERT INTO VergiMuafiyetleri (Kod,Aciklama) 
Select '0','YOK'  WHERE NOT EXISTS (select 1 from VergiMuafiyetleri where Kod = '0')

go--
----------------------------------------------------------------

IF (Select COUNT(*) from Parametre where Param = 'Vergi Muafiyet Kodu')  = 0  
BEGIN
	Insert into Parametre Select'Vergi Muafiyet Kodu','0'
END
ELSE IF  (Select COUNT(*) from Parametre where Param = 'Vergi Muafiyet Kodu' and (Deger = '' or Deger is null))  > 0  
BEGIN
	update Parametre SET Deger = '0' where Param = 'Vergi Muafiyet Kodu'	
END;
go--

-------------------------------------------------------------------
   IF  EXISTS (SELECT *  FROM sys.key_constraints WHERE  name='UQ_Doviz_IsoKodu')
 BEGIN 

 ALTER TABLE Doviz_Iso_Birim  DROP CONSTRAINT UQ_Doviz_IsoKodu
end
else
begin
ALTER TABLE Doviz_Iso_Birim ADD CONSTRAINT UQ_Doviz_IsoKodu UNIQUE(IsoKodu)
 end
go--

---------------------------------------------------------------------------
  IF  EXISTS (SELECT *  FROM sys.key_constraints WHERE  name='UQ_StokFiyat_FiyatNo')
 BEGIN 
--select 'drop' 
ALTER TABLE [StokFiyatParametre]  DROP CONSTRAINT UQ_StokFiyat_FiyatNo
end
else begin
--select 'add'
ALTER TABLE [StokFiyatParametre] ADD CONSTRAINT UQ_StokFiyat_FiyatNo UNIQUE(FiyatNo)
end;
go--

 IF OBJECT_ID('tempdb..#StokFiyatParametre') IS NULL
 BEGIN 
	  CREATE TABLE [dbo].[#StokFiyatParametre](
		[NoId] [int] IDENTITY(1,1) NOT NULL,
		[FiyatNo] [int] NOT NULL UNIQUE,
		[FiyatAdi] [nvarchar](30) NULL,
		[KDV_DH] [nvarchar](1) NULL,
		[DovizKodu] [nvarchar](3) NULL
	) ON [PRIMARY]
END
go--
 IF NOT EXISTS (SELECT *  FROM sys.tables WHERE  name='StokFiyatParametre')
 BEGIN 
 CREATE TABLE [dbo].[StokFiyatParametre](
	[NoId] [int] IDENTITY(1,1) NOT NULL,
	[FiyatNo] [int] NOT NULL UNIQUE,
	[FiyatAdi] [nvarchar](30) NULL,
	[KDV_DH] [nvarchar](1) NULL,
	[DovizKodu] [nvarchar](3) NULL
) ON [PRIMARY]
 end
go--
---------------------------------------------------------------------------
 SET IDENTITY_INSERT [dbo].[#StokFiyatParametre] ON 
 ---------------------------------------------------------------------------
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (1, 1, N'ALIŞ', N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (2, 2, N'SATIŞ', N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (3, 3, N'', N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (4, 4, N'PRK.SATIŞ', N'D', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (5, 5, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (6, 6, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (7, 7, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (8, 8, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (9, 9, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (10, 10, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (11, 11, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (12, 12, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (13, 13, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (14, 14, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (15, 15, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (16, 16, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (17, 17, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (18, 18, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (19, 19, NULL, N'H', N'YP')
INSERT [dbo].[#StokFiyatParametre] ( [NoId],[FiyatNo], [FiyatAdi], [KDV_DH], [DovizKodu]) VALUES (20, 20, NULL, N'H', N'YP')

SET IDENTITY_INSERT [dbo].[#StokFiyatParametre] OFF
go--

insert into StokFiyatParametre (FiyatNo, FiyatAdi, KDV_DH, DovizKodu)
SELECT FiyatNo, FiyatAdi, KDV_DH, DovizKodu FROM  #StokFiyatParametre where FiyatNo not in (select FiyatNo from StokFiyatParametre)
go--
 --select * from [StokFiyatParametre]
 --select * from [#StokFiyatParametre]

go--
 ---------------------------------------------------------------------------
  IF NOT EXISTS (SELECT *  FROM sys.tables WHERE  name='Doviz_Iso_Birim')
 BEGIN 
CREATE TABLE Doviz_Iso_Birim (IsoKodu nvarchar(5)  NOT NULL ,IsoAciklama nvarchar(250))
 end
go--
-----------------------------------------------------------------

if exists (select * from sys.procedures where name='sp_FiyatGetir')
drop proc sp_FiyatGetir
go--
-----------------------------------------------------------------
CREATE    proc sp_FiyatGetir                               
@IslemTuru varchar(50),  --'AlisFiyati'  , 'AlisIadeFiyati' , 'PerakendeFiyati'                              
@CariKodu varchar(20),                              
@StokKodu varchar(30),                               
@Tarih varchar(8),                        
@IslemNo int                        
as                              
                              
Declare @KDVHaricFiyat float;      
Declare @KDVHaric float;    
Declare @Iskonto1 float;                              
Declare @Iskonto2 float;                              
Declare @Iskonto3 float;                              
Declare @Iskonto4 float;                              
Declare @AlismiSatismi varchar(9);                              
begin                              
  Declare @AlisFiyatiAlan varchar(10);                              
  Declare @SatisFiyatiAlan varchar(10);                              
  Declare @PerakendeFiyatiAlan varchar(10);                            
  Declare @KDV float;                           
                              
  Declare @AlisFiyati float;                              
  Declare @SatisFiyati float;                              
  Declare @PerakendeFiyati float;                              
  Declare @Sql nvarchar(500);                              
  Declare @DonemselFiyatUygulansin varchar(2);                              
  Declare @CariFiyatGrubuKullanilsin varchar(2);                           
  Declare @DovizKodu varchar(20);                            
  Declare @DovizKoduAlisAlan varchar(20);                            
  Declare @DovizKoduSatisAlan varchar(20);         
        
    if (@IslemTuru='AlisFiyati' )                              
      select @Iskonto1=AlisIndirimYuzde, @Iskonto2=AlisIndirimYuzde2,@Iskonto3=AlisIndirimYuzde3,@Iskonto4=AlisIndirimYuzde4,@KDV = AlisKdv from STOKKARTI where Kodu=@StokKodu                              
    if (@IslemTuru='SatisFiyati' or @IslemTuru='PerakendeFiyati')                              
      select @Iskonto1=SatisIndirimYuzde, @Iskonto2=SatisIndirimYuzde2,@Iskonto3=SatisIndirimYuzde3,@Iskonto4=SatisIndirimYuzde4,@KDV = SatisKdv from STOKKARTI where Kodu=@StokKodu                              
          
      
                              
  if @IslemTuru='AlisFiyati'                               
    Set @AlismiSatismi='Alış'                              
  if @IslemTuru='SatisFiyati'                            
    Set @AlismiSatismi='Satış';                    
                               
  if @IslemTuru='AlisFiyati' or @IslemTuru='SatisFiyati' or @IslemTuru='PerakendeFiyati'                    
    begin                            
   --0 ise hayır, -1 ise evet                              
   select @DonemselFiyatUygulansin=Deger from Parametre                               
  where Param ='Kampanya Fiyatları Kullanılsın'                              
   select @CariFiyatGrubuKullanilsin=Deger from Parametre                               
  where Param ='Faturalarda Cari Fiyat Grubu Uygulansın'            
        
      
  declare @KDVDahilFiyat float                        
  declare @KDVDahil float 
 set @KDVDahilFiyat=@KDVHaricFiyat*(@KDV+100)/100        
        
   if (@DonemselFiyatUygulansin='-1')           
      
  begin                              
    select TOP (1) @KDVHaricFiyat = KdvHaricFiyat,      
   @KDVDahilFiyat = KdvDahilFiyat,      
   @Iskonto1=Iskonto1,                              
   @Iskonto2=Iskonto2,                              
   @Iskonto3=Iskonto3,                              
   @Iskonto4=Iskonto4                               
   from Vstk_CariDonemselFiyatlar where CariKodu = @CariKodu                              
   and StokKodu = @StokKodu                                        
   and FiyatTipi = @AlismiSatismi and                              
   @Tarih between BaslangicTarihi and BitisTarihi                               
   order by SiraNo DESC                              
  end;                               
                                 if (@KDVHaricFiyat is null)                              
  begin                              
    if (@CariFiyatGrubuKullanilsin='-1')                              
   begin                              
  select @AlisFiyatiAlan = AlisFiyatiH, @SatisFiyatiAlan=SatisFiyatiH, @PerakendeFiyatiAlan=PerakendeFiyati                               
    from CariFiyatlari                               
    where FiyatGrupAdi = (select ISNULL(FiyatGrupAdi,'F.G.A.YOK') as FiyatGrupAdi from                               
    AMUSTERI where MUSKOD = @CariKodu)                              
   end;                            
                                        
   if (@AlisFiyatiAlan is null)                              
   begin                              
   Set @AlisFiyatiAlan = 'F1FiyatH';                              
   Set @SatisFiyatiAlan = 'F2FiyatH';                              
   Set @PerakendeFiyatiAlan = 'F4FiyatH';                              
   end;                            
                            
   Set @DovizKoduAlisAlan = LEFT(@AlisFiyatiAlan,2)+'DovizKodu';                    
                               
   Set @DovizKoduSatisAlan = LEFT(@SatisFiyatiAlan,2)+'DovizKodu';                              
                     
   if (@IslemTuru='PerakendeFiyati')                  
     Set @DovizKoduSatisAlan = LEFT(@PerakendeFiyatiAlan,2)+'DovizKodu';                              
                               
   if (@IslemTuru='AlisFiyati' or @IslemTuru='AlisIadeFiyati')                              
     Set @Sql='select @KdvHaricFiyat='+ @AlisFiyatiAlan+',@DovizKodu='+@DovizKoduAlisAlan+' from StokFiyat where Kodu='''+@StokKodu+'''';                              
   if (@IslemTuru='SatisFiyati' or @IslemTuru='SatisIadeFiyati')                              
     Set @Sql='select @KdvHaricFiyat='+ @SatisFiyatiAlan+',@DovizKodu='+@DovizKoduSatisAlan+' from StokFiyat where Kodu='''+@StokKodu+'''';                    
   if (@IslemTuru='PerakendeFiyati')                  
     Set @Sql='select @KdvHaricFiyat='+ @PerakendeFiyatiAlan+',@DovizKodu='+@DovizKoduSatisAlan+' from StokFiyat where Kodu='''+@StokKodu+'''';                                                 
                                         
   execute sp_executesql @Sql,N'@KdvHaricFiyat float Output, @DovizKodu varchar(20) Output ', @KdvHaricFiyat=@KDVHaricFiyat Output, @DovizKodu=@DovizKodu Output;                            
   select @KDVHaric = @KDVHaricFiyat                       
   Select @KDVHaricFiyat = @KDVHaricFiyat * (select GunFiyati from DOVIZT where DovizKodu=@DovizKodu)  
    
     
   declare @F1FifoFiyat   float  
   SET @F1FifoFiyat = (select   (F1FiyatH * (100  + SatisKdv) / 100) * (select GunFiyati from DOVIZT where DovizKodu=@DovizKodu)  from StokFiyat where Kodu = @StokKodu)  
              
              
   --print 'DovizKodu='+@DovizKodu+' Sql='+@sql                          
    end;                              
                              
    end;                      
  if (@IslemTuru='AlisIadeFiyati')                    
    begin                    
      select top 1 @KDVHaricFiyat=BirimFiyat, @Iskonto1=Iskonto1, @Iskonto2=Iskonto2,@Iskonto3=Iskonto3,@Iskonto4=Iskonto4, @KDV=Kdv  from STOKHAR where CariKodu = @CariKodu and                     
  IslemTuru = 'Alış' and StokKodu=@StokKodu                    
  order by NoId desc                    
 end;                    
  if (@IslemTuru='SatisIadeFiyati')                    
    begin                    
      select top 1 @KDVHaricFiyat=BirimFiyat, @Iskonto1=Iskonto1, @Iskonto2=Iskonto2,@Iskonto3=Iskonto3,@Iskonto4=Iskonto4, @KDV=Kdv from STOKHAR where CariKodu = @CariKodu and                     
   IslemTuru in  ('Satış','Prk.Satış')  and StokKodu=@StokKodu                    
   order by NoId desc                    
 end;                  
                
declare @strIslemNo varchar                        
set @strIslemNo=convert(varchar,@IslemNo)                        
--declare @KDVDahilFiyat float       
set @KDVDahil = @KDVHaric*(@KDV+100)/100                          
set @KDVDahilFiyat=@KDVHaricFiyat*(@KDV+100)/100                         
                  
select  @KdvHaricFiyat as KDVHaricFiyat,@KDVDahilFiyat as KDVDahilFiyat,
	   @Iskonto1 as Iskonto1,@Iskonto2 as Iskonto2, @Iskonto3 as Iskonto3,@Iskonto4 as Iskonto4,
	   @KDV as KDV , @DonemselFiyatUygulansin AS KampanyaFyt, @CariFiyatGrubuKullanilsin FiyatGrp,@F1FifoFiyat F1FifoFiyat,      
       @DovizKodu as DovizKodu,@KDVDahil KDDovizFiyati,@KDVHaric KHDovizFiyati
               
end             
go--
---------------------------------- ----------------
ALTER LOGIN [Sbs_Net] WITH PASSWORD=N'!Sbs_Net!95', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[Türkçe], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
go--
ALTER LOGIN [Sbs_Net] DISABLE
go--
ALTER SERVER ROLE [sysadmin] ADD MEMBER [Sbs_Net]
go--
ALTER LOGIN [Sbs_Net] ENABLE
go--

IF not  EXISTS (SELECT *  FROM sys.tables WHERE  name='CekmeceHareket')
 BEGIN 
CREATE TABLE CekmeceHareket (
	Id int NOT NULL,
	Kayit_Tarihi smalldatetime NULL,
	Kullanici_Id int NULL,
	Aciklama nvarchar(100) NULL,
	Onay bit NULL,
	Kaynak char(1) NULL
)
end
go--
 IF   EXISTS (SELECT *  FROM sys.tables WHERE  name='BAAciklamaTanim')
 BEGIN 
	drop table [BAAciklamaTanim]
	end
go--

CREATE TABLE [dbo].[BAAciklamaTanim](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Tanim] [nvarchar](30) not NULL 
) ON [PRIMARY]
go--
ALTER TABLE [BAAciklamaTanim] ADD CONSTRAINT UQ_BAAciklama_Tanim UNIQUE(Tanim)
go--
SET IDENTITY_INSERT [dbo].[BAAciklamaTanim] ON 
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (1, N'Alış')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (2, N'Alış İade')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (3, N'Alacak')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (4, N'Borç')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (5, N'G.Virman')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (6, N'Gel.Havale')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (7, N'Gön.Havale')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (8, N'KK.Tahsilat')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (9, N'M.Mahsup')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (10, N'Mutabakat')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (11, N'Prk.Satış')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (12, N'Satış')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (13, N'Satış İade')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (14, N'Senet Girişi')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (15, N'Senet Çıkışı')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (16, N'Tahsilat')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (17, N'Virman')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (18, N'Çek İade')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (19, N'Çek Girişi')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (20, N'Çek Çıkışı')
go--
INSERT [dbo].[BAAciklamaTanim] ([Id], [Tanim]) VALUES (21, N'Ödeme')
go--
SET IDENTITY_INSERT [dbo].[BAAciklamaTanim] OFF
go--
SET ANSI_PADDING ON
go--
if  not  exists (select * from dbo.syscolumns where id = object_id(N'DOVIZT') and name=N'HPS_Gorunsun')
begin
ALTER TABLE DOVIZT ADD HPS_Gorunsun bit default 1
end
go--
--------------------------------------------------------------
update KullaniciAyarlari set Deger='YOK'  where Ayar  ='Kullanılacak Modem Adı' AND Deger='Default'
go--
----------------------------------------------------------------

INSERT INTO VergiMuafiyetleri (Kod,Aciklama) 
Select '0','YOK'  WHERE NOT EXISTS (select 1 from VergiMuafiyetleri where Kod = '0')

go--
----------------------------------------------------------------

IF (Select COUNT(*) from Parametre where Param = 'Vergi Muafiyet Kodu')  = 0  
BEGIN
	Insert into Parametre Select'Vergi Muafiyet Kodu','0'
END
ELSE IF  (Select COUNT(*) from Parametre where Param = 'Vergi Muafiyet Kodu' and (Deger = '' or Deger is null))  > 0  
BEGIN
	update Parametre SET Deger = '0' where Param = 'Vergi Muafiyet Kodu'	
END;
go--

 ---------------------------------------------------------------------------
  IF NOT EXISTS (SELECT *  FROM sys.tables WHERE  name='Doviz_Iso_Birim')
 BEGIN 
CREATE TABLE Doviz_Iso_Birim (IsoKodu nvarchar(5) UNIQUE NOT NULL ,IsoAciklama nvarchar(250))
 end
go--
-----------------------------------------------------------------
if exists (select * from sys.procedures where name='sp_FiyatGetir')
drop proc sp_FiyatGetir
go--
-----------------------------------------------------------------
create  PROC [dbo].[sp_FiyatGetir]
    @IslemTuru VARCHAR(50),  -- 'AlisFiyati', 'AlisIadeFiyati', 'PerakendeFiyati'
    @CariKodu  VARCHAR(20),
    @StokKodu  VARCHAR(30),
    @Tarih     VARCHAR(8),
    @IslemNo   INT
AS

DECLARE @KDVHaricFiyat FLOAT;
DECLARE @KDVHaric      FLOAT;

DECLARE @Iskonto1 FLOAT;
DECLARE @Iskonto2 FLOAT;
DECLARE @Iskonto3 FLOAT;
DECLARE @Iskonto4 FLOAT;

DECLARE @IskontoParam BIT;
DECLARE @AlismiSatismi VARCHAR(9);

BEGIN
    DECLARE @AlisFiyatiAlan      VARCHAR(10);
    DECLARE @SatisFiyatiAlan     VARCHAR(10);
    DECLARE @PerakendeFiyatiAlan VARCHAR(10);

    DECLARE @KDV FLOAT;

    DECLARE @AlisFiyati      FLOAT;
    DECLARE @SatisFiyati     FLOAT;
    DECLARE @PerakendeFiyati FLOAT;

    DECLARE @Sql NVARCHAR(500);

    DECLARE @DonemselFiyatUygulansin   VARCHAR(2);
    DECLARE @CariFiyatGrubuKullanilsin VARCHAR(2);

    DECLARE @DovizKodu          VARCHAR(20);
    DECLARE @DovizKoduAlisAlan  VARCHAR(20);
    DECLARE @DovizKoduSatisAlan VARCHAR(20);

    SELECT
        @IskontoParam = CAST(YUZDE AS BIT)
    FROM AMUSTERI
    WHERE MUSKOD = @CariKodu;

    IF (@IslemTuru = 'AlisFiyati')
        SELECT
            @Iskonto1 = AlisIndirimYuzde,
            @Iskonto2 = AlisIndirimYuzde2,
            @Iskonto3 = AlisIndirimYuzde3,
            @Iskonto4 = AlisIndirimYuzde4,
            @KDV      = AlisKdv
        FROM STOKKARTI
        WHERE Kodu = @StokKodu;

    IF (@IslemTuru = 'SatisFiyati' OR @IslemTuru = 'PerakendeFiyati')
        SELECT
            @Iskonto1 = SatisIndirimYuzde,
            @Iskonto2 = SatisIndirimYuzde2,
            @Iskonto3 = SatisIndirimYuzde3,
            @Iskonto4 = SatisIndirimYuzde4,
            @KDV      = SatisKdv
        FROM STOKKARTI
        WHERE Kodu = @StokKodu;

    IF @IslemTuru = 'AlisFiyati'
        SET @AlismiSatismi = 'Alış';

    IF @IslemTuru = 'SatisFiyati'
        SET @AlismiSatismi = 'Satış';

    IF @IslemTuru = 'AlisFiyati'
        OR @IslemTuru = 'SatisFiyati'
        OR @IslemTuru = 'PerakendeFiyati'
    BEGIN
        SELECT
            @DonemselFiyatUygulansin = Deger
        FROM Parametre
        WHERE Param = 'Kampanya Fiyatları Kullanılsın';

        SELECT
            @CariFiyatGrubuKullanilsin = Deger
        FROM Parametre
        WHERE Param = 'Faturalarda Cari Fiyat Grubu Uygulansın';

        DECLARE @KDVDahilFiyat FLOAT;
        DECLARE @KDVDahil      FLOAT;

        SET @KDVDahilFiyat = @KDVHaricFiyat * (@KDV + 100) / 100;

        IF (@DonemselFiyatUygulansin = '-1')
        BEGIN
            SELECT TOP (1)
                @KDVHaricFiyat = KdvHaricFiyat,
                @KDVDahilFiyat = KdvDahilFiyat,
                @Iskonto1      = Iskonto1,
                @Iskonto2      = Iskonto2,
                @Iskonto3      = Iskonto3,
                @Iskonto4      = Iskonto4
            FROM Vstk_CariDonemselFiyatlar
            WHERE CariKodu  = @CariKodu
              AND StokKodu  = @StokKodu
              AND FiyatTipi = @AlismiSatismi
              AND @Tarih BETWEEN BaslangicTarihi AND BitisTarihi
            ORDER BY SiraNo DESC;
        END;

        IF (@KDVHaricFiyat IS NULL)
        BEGIN
            IF (@CariFiyatGrubuKullanilsin = '-1')
            BEGIN
                SELECT
                    @AlisFiyatiAlan      = AlisFiyatiH,
                    @SatisFiyatiAlan     = SatisFiyatiH,
                    @PerakendeFiyatiAlan = PerakendeFiyati
                FROM CariFiyatlari
                WHERE FiyatGrupAdi =
                (
                    SELECT ISNULL(FiyatGrupAdi, 'F.G.A.YOK')
                    FROM AMUSTERI
                    WHERE MUSKOD = @CariKodu
                );
            END;

            IF (@AlisFiyatiAlan IS NULL)
            BEGIN
                SET @AlisFiyatiAlan      = 'F1FiyatH';
                SET @SatisFiyatiAlan     = 'F2FiyatH';
                SET @PerakendeFiyatiAlan = 'F4FiyatH';
            END;

            SET @DovizKoduAlisAlan  = LEFT(@AlisFiyatiAlan, 2) + 'DovizKodu';
            SET @DovizKoduSatisAlan = LEFT(@SatisFiyatiAlan, 2) + 'DovizKodu';

            IF (@IslemTuru = 'PerakendeFiyati')
                SET @DovizKoduSatisAlan = LEFT(@PerakendeFiyatiAlan, 2) + 'DovizKodu';

            IF (@IslemTuru = 'AlisFiyati' OR @IslemTuru = 'AlisIadeFiyati')
                SET @Sql =
                    'select @KdvHaricFiyat=' + @AlisFiyatiAlan +
                    ',@DovizKodu=' + @DovizKoduAlisAlan +
                    ' from StokFiyat where Kodu=''' + @StokKodu + '''';

            IF (@IslemTuru = 'SatisFiyati' OR @IslemTuru = 'SatisIadeFiyati')
                SET @Sql =
                    'select @KdvHaricFiyat=' + @SatisFiyatiAlan +
                    ',@DovizKodu=' + @DovizKoduSatisAlan +
                    ' from StokFiyat where Kodu=''' + @StokKodu + '''';

            IF (@IslemTuru = 'PerakendeFiyati')
                SET @Sql =
                    'select @KdvHaricFiyat=' + @PerakendeFiyatiAlan +
                    ',@DovizKodu=' + @DovizKoduSatisAlan +
                    ' from StokFiyat where Kodu=''' + @StokKodu + '''';

            EXEC sp_executesql
                @Sql,
                N'@KdvHaricFiyat float OUTPUT, @DovizKodu varchar(20) OUTPUT',
                @KdvHaricFiyat = @KDVHaricFiyat OUTPUT,
                @DovizKodu     = @DovizKodu OUTPUT;

            SELECT @KDVHaric = @KDVHaricFiyat;

            SELECT
                @KDVHaricFiyat = @KDVHaricFiyat *
                (SELECT GunFiyati FROM DOVIZT WHERE DovizKodu = @DovizKodu);

            DECLARE @F1FifoFiyat FLOAT;

            SET @F1FifoFiyat =
            (
                SELECT
                    (F1FiyatH * (100 + SatisKdv) / 100) *
                    (SELECT GunFiyati FROM DOVIZT WHERE DovizKodu = @DovizKodu)
                FROM StokFiyat
                WHERE Kodu = @StokKodu
            );
        END;
    END;

    IF (@IslemTuru = 'AlisIadeFiyati')
        SELECT TOP 1
            @KDVHaricFiyat = BirimFiyat,
            @Iskonto1     = Iskonto1,
            @Iskonto2     = Iskonto2,
            @Iskonto3     = Iskonto3,
            @Iskonto4     = Iskonto4,
            @KDV          = Kdv
        FROM STOKHAR
        WHERE CariKodu = @CariKodu
          AND IslemTuru = 'Alış'
          AND StokKodu = @StokKodu
        ORDER BY NoId DESC;

    IF (@IslemTuru = 'SatisIadeFiyati')
        SELECT TOP 1
            @KDVHaricFiyat = BirimFiyat,
            @Iskonto1     = Iskonto1,
            @Iskonto2     = Iskonto2,
            @Iskonto3     = Iskonto3,
            @Iskonto4     = Iskonto4,
            @KDV          = Kdv
        FROM STOKHAR
        WHERE CariKodu = @CariKodu
          AND IslemTuru IN ('Satış', 'Prk.Satış')
          AND StokKodu = @StokKodu
        ORDER BY NoId DESC;

    DECLARE @strIslemNo VARCHAR;

    SET @strIslemNo = CONVERT(VARCHAR, @IslemNo);

    SET @KDVDahil      = @KDVHaric * (@KDV + 100) / 100;
    SET @KDVDahilFiyat = @KDVHaricFiyat * (@KDV + 100) / 100;

    IF @IskontoParam = 0
    BEGIN
        SET @Iskonto1 = 0;
        SET @Iskonto2 = 0;
        SET @Iskonto3 = 0;
        SET @Iskonto4 = 0;
    END;

    SELECT
        @KDVHaricFiyat AS KDVHaricFiyat,
        @KDVDahilFiyat AS KDVDahilFiyat,
        @Iskonto1      AS Iskonto1,
        @Iskonto2      AS Iskonto2,
        @Iskonto3      AS Iskonto3,
        @Iskonto4      AS Iskonto4,
        @KDV           AS KDV,
        @DonemselFiyatUygulansin AS KampanyaFyt,
        @CariFiyatGrubuKullanilsin AS FiyatGrp,
        @F1FifoFiyat   AS F1FifoFiyat,
        @DovizKodu     AS DovizKodu,
        @KDVDahil      AS KDDovizFiyati,
        @KDVHaric      AS KHDovizFiyati;
END;



go--
---------------------------------- ----------------
ALTER LOGIN [Sbs_Net] WITH PASSWORD=N'!Sbs_Net!95', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[Türkçe], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
go--
ALTER LOGIN [Sbs_Net] DISABLE
go--
ALTER SERVER ROLE [sysadmin] ADD MEMBER [Sbs_Net]
go--
ALTER LOGIN [Sbs_Net] ENABLE
go--
  update STOKKARTI SET StokTipi ='+ Ürün' WHERE StokTipi IN   ('','Ürün')
go--
---------------------------------------------------------------------------------------------
if  not  exists (select * from dbo.syscolumns where id = object_id(N'DOVIZT') and name=N'AktifPasif')
begin
ALTER TABLE DOVIZT ADD AktifPasif bit default 1
end
go--
 
---------------------------------------------------------------------------------------------

UPDATE DOVIZT SET AktifPasif = 1 where AktifPasif<>0
go--
---------------------------------------------------------------------------------------------
 IF NOT EXISTS (SELECT *  FROM sys.tables WHERE  name='KasaPaletKodTanim')
 BEGIN 
CREATE TABLE KasaPaletKodTanim (Id INT IDENTITY(1,1),KasaNo int, KasaAdi nvarchar(50))
end
go--
---------------------------------------------------------------------------------------------
if exists (select * from sys.procedures where name='StokNo_CiftNo_Degistir')
drop proc StokNo_CiftNo_Degistir
go--
---------------------------------------------------------------------------------------------
CREATE   PROC StokNo_CiftNo_Degistir
AS   
BEGIN  
	DECLARE @StokNo int,@NoId int,@NoId2 int

	DECLARE db_cursor CURSOR FOR 
	SELECT StokNo,MIN(NoId) NoId from  STOKKARTI group by StokNo having count(*) >  1 
	OPEN db_cursor  

	FETCH NEXT FROM db_cursor INTO @StokNo,@NoId 

	WHILE @@FETCH_STATUS = 0  
	BEGIN
	
		DECLARE db_cursor2 CURSOR FOR 
		SELECT NoId FROM STOKKARTI WHERE StokNo = @StokNo and NoId <> @NoId

		OPEN db_cursor2  
		FETCH NEXT FROM db_cursor2 INTO @NoId2  

		WHILE @@FETCH_STATUS = 0  
		BEGIN  
			  update STOKKARTI  SET StokNo = (select MAX(StokNo) + 1 from STOKKARTI) where  NoId = @NoId2			  
			  UPDATE n  SET StokNo = k2.StokNo  FROM STOKHAR  n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu and k2.NoId = @NoId2
			  UPDATE n  SET StokNo = k2.StokNo  FROM SIPARISHAR   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu and k2.NoId = @NoId2  
			  UPDATE n  SET StokNo = k2.StokNo  FROM StokBarkodlari   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu  and k2.NoId = @NoId2 
			  UPDATE n  SET StokNo = k2.StokNo  FROM StokFiyat   n ,  STOKKARTI k2 where n.Kodu =k2.Kodu  and k2.NoId = @NoId2 
			  UPDATE n  SET StokNo = k2.StokNo  FROM StokDB   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu  and k2.NoId = @NoId2 
			  UPDATE n  SET StokNo = k2.StokNo  FROM StokHarLog   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu and k2.NoId = @NoId2  
			  UPDATE n  SET StokNo = k2.StokNo  FROM MuadilStoklar   n ,  STOKKARTI k2 where n.MuadilStokKodu =k2.Kodu and k2.NoId = @NoId2  
			  UPDATE n  SET StokNo = k2.StokNo  FROM Buton   n ,  STOKKARTI k2 where n.ButonDegeri =k2.Kodu   and k2.NoId = @NoId2
			  UPDATE n  SET StokNo = k2.StokNo  FROM PDegFiyatlar   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu  and k2.NoId = @NoId2 
			  UPDATE n  SET StokNo = k2.StokNo  FROM SipHar   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu and k2.NoId = @NoId2  
			  UPDATE n  SET StokNo = k2.StokNo  FROM TEKLIFHAR   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu and k2.NoId = @NoId2  
			  UPDATE n  SET StokNo = k2.StokNo  FROM Tevkifat   n ,  STOKKARTI k2 where n.Kod =k2.Kodu and k2.NoId = @NoId2   

		FETCH NEXT FROM db_cursor2 INTO @NoId2 
		END 

		CLOSE db_cursor2 
		DEALLOCATE db_cursor2

	FETCH NEXT FROM db_cursor INTO @StokNo,@NoId  
	END 

	CLOSE db_cursor  
	DEALLOCATE db_cursor
END;  
go--

DELETE GridView WHERE GirdAdi='Hızlı Stok Girişi Gridi'
DELETE GridView WHERE GirdAdi='Fatura İşlemleri İşlem Gridi'
go--
if not exists (SELECT 1 FROM VTGuncellemeleri WHERE VTVersiyon='7.2.0')
BEGIN
insert into VTGuncellemeleri (VTVersiyon, SonIslemNo, TarihSaat, Prg)
VALUES ('7.2.0',(select ISLEMNO from ADIGSABITLER ),GETDATE(),'OM')
END
go--

IF NOT EXISTS (SELECT *  FROM sys.tables WHERE  name='KasaPaletKodTanim')
 BEGIN 
CREATE TABLE KasaPaletKodTanim (Id INT IDENTITY(1,1),KasaNo int, KasaAdi nvarchar(50))
end
go--
-------------------------------------------------------------------------------

if  not  exists (select * from dbo.syscolumns where id = object_id(N'DOVIZT') and name=N'AktifPasif')
begin
ALTER TABLE DOVIZT ADD AktifPasif bit default 1
end
go--
--------------------------------------------------------------------------------

UPDATE DOVIZT SET AktifPasif = 1
go--


if exists (select * from sys.procedures where name='StokNo_CiftNo_Degistir')
drop proc StokNo_CiftNo_Degistir
go--
-------------------------------------------------------------------------------

CREATE   PROC StokNo_CiftNo_Degistir
AS   
BEGIN  
	DECLARE @StokNo int,@NoId int,@NoId2 int

	DECLARE db_cursor CURSOR FOR 
	SELECT StokNo,MIN(NoId) NoId from  STOKKARTI group by StokNo having count(*) >  1 
	OPEN db_cursor  

	FETCH NEXT FROM db_cursor INTO @StokNo,@NoId 

	WHILE @@FETCH_STATUS = 0  
	BEGIN
	
		DECLARE db_cursor2 CURSOR FOR 
		SELECT NoId FROM STOKKARTI WHERE StokNo = @StokNo and NoId <> @NoId

		OPEN db_cursor2  
		FETCH NEXT FROM db_cursor2 INTO @NoId2  

		WHILE @@FETCH_STATUS = 0  
		BEGIN  
			  update STOKKARTI  SET StokNo = (select MAX(StokNo) + 1 from STOKKARTI) where  NoId = @NoId2			  
			  UPDATE n  SET StokNo = k2.StokNo  FROM STOKHAR  n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu and k2.NoId = @NoId2
			  UPDATE n  SET StokNo = k2.StokNo  FROM SIPARISHAR   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu and k2.NoId = @NoId2  
			  UPDATE n  SET StokNo = k2.StokNo  FROM StokBarkodlari   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu  and k2.NoId = @NoId2 
			  UPDATE n  SET StokNo = k2.StokNo  FROM StokFiyat   n ,  STOKKARTI k2 where n.Kodu =k2.Kodu  and k2.NoId = @NoId2 
			  UPDATE n  SET StokNo = k2.StokNo  FROM StokDB   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu  and k2.NoId = @NoId2 
			  UPDATE n  SET StokNo = k2.StokNo  FROM StokHarLog   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu and k2.NoId = @NoId2  
			  UPDATE n  SET StokNo = k2.StokNo  FROM MuadilStoklar   n ,  STOKKARTI k2 where n.MuadilStokKodu =k2.Kodu and k2.NoId = @NoId2  
			  UPDATE n  SET StokNo = k2.StokNo  FROM Buton   n ,  STOKKARTI k2 where n.ButonDegeri =k2.Kodu   and k2.NoId = @NoId2
			  UPDATE n  SET StokNo = k2.StokNo  FROM PDegFiyatlar   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu  and k2.NoId = @NoId2 
			  UPDATE n  SET StokNo = k2.StokNo  FROM SipHar   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu and k2.NoId = @NoId2  
			  UPDATE n  SET StokNo = k2.StokNo  FROM TEKLIFHAR   n ,  STOKKARTI k2 where n.StokKodu =k2.Kodu and k2.NoId = @NoId2  
			  UPDATE n  SET StokNo = k2.StokNo  FROM Tevkifat   n ,  STOKKARTI k2 where n.Kod =k2.Kodu and k2.NoId = @NoId2   

		FETCH NEXT FROM db_cursor2 INTO @NoId2 
		END 

		CLOSE db_cursor2 
		DEALLOCATE db_cursor2

	FETCH NEXT FROM db_cursor INTO @StokNo,@NoId  
	END 

	CLOSE db_cursor  
	DEALLOCATE db_cursor
END;  
      
go--
-------------------------------------------------------------------------------
if exists (select * from sys.procedures where name='sp_SN_Bakim')
drop proc sp_SN_Bakim
go--
------------------------------------------------------------------------------
CREATE   PROC sp_SN_Bakim        
AS    
BEGIN         
 UPDATE STOKHAR SET IslemTuru ='Mal Sayımı' where IslemTuru like '%Mal Say%'  
 UPDATE STOKHARDETBAG SET IslemTuru ='Mal Sayımı' where IslemTuru like '%Mal Say%' 
  ALTER TABLE STOKHAR disable TRIGGER STOKHAR_Degisim
 exec StokNo_CiftNo_Degistir
 EXEC spBAKIM
 EXEC sp_Grup_Bakim          
 EXEC sp_StokDoviz_Bakim          
 EXEC sp_StokFiyat_Bakim          
 EXEC sp_StokFiyatBakim           
 EXEC sp_Kart_Bakim        
 EXEC sp_BAKIM_KOLON_UPDATE      
 EXEC sp_Hareket_Bakim    
 EXEC sp_BirimBarkod_Aktarim    
 EXEC sp_Bakim_Doviz_KdvDH_Update  
 exec sp_OdemePlaniKontrol  
  ALTER TABLE STOKHAR ENABLE TRIGGER STOKHAR_Degisim
END  

go--
------------------------------------------------------------------------------
IF  EXISTS (SELECT *  FROM sys.triggers WHERE  name='STOKHAR_Degisim')
 BEGIN 
 drop trigger STOKHAR_Degisim
 end
 go--
 --------------------------------------------------------------------------------

CREATE   trigger [dbo].[STOKHAR_Degisim] on [dbo].[STOKHAR] for  DELETE ,UPDATE  
 AS  
BEGIN  	
insert into [StokHarLog]   
Select  [NoId] ,[IslemNo] ,[IslemTuru] ,[CariNo] ,[StokNo] ,[StokKodu],[Miktar],[Birim],[BirimFiyat] ,  
  CONVERT(nvarchar(20) , [Iskonto1]) + ';' + CONVERT(nvarchar(20) , [Iskonto2]) + ';' + CONVERT(nvarchar(20) , [Iskonto3]) + ';' + CONVERT(nvarchar(20) , [Iskonto4]),  
  [SiparisNo],[SiparisTarihi],[Kdv] ,[FisTuru] ,[FaturaNo] ,[FaturaTarihi] ,[Satici] ,[DovizTut] ,[DovizKodu],[Depo] ,[KULNO],  
  CONVERT(nvarchar(20) , [AltIskYuzde1]) + ';' + CONVERT(nvarchar(20) , [AltIskYuzde2]) + ';' + CONVERT(nvarchar(20) , [AltIskYuzde3]),  
  [IslemNo3] , [Departman] , [SonTutar] , [SonTutarDov] , [SatMasrafTutari] , GETDATE()    
from deleted  where NOT EXISTS (select SayiAlan1 from TakasTablosu where KarekterAlan1 = 'RanrosSatisBekletme')
end
go--
------------------------------------------------------------------------------------------------------------------------------------------  
 if exists (select * from sys.procedures where name='sp_Hareket_Bakim')
drop proc sp_Hareket_Bakim
go--
-------------------------------------------------------------------------------

 CREATE     PROCEDURE sp_Hareket_Bakim        
AS        
         
DELETE FROM STOKHAR WHERE Miktar in (NULL,'',' ',0)       
DELETE FROM SIPARISHAR WHERE Miktar   in (NULL,'',' ',0)       
DELETE FROM TEKLIFHAR WHERE Miktar in (NULL,'',' ',0)         
 ---DEPO VİRMANDAN GELEN İŞLEMNO OLMAYAN KAYITLAR İÇİN        
UPDATE STOKHAR SET IslemNo=IslemNo-1 where IslemNo in( select IslemNo from STOKHAR SH WHERE NOT EXISTS       
(SELECT * FROM STOKHARDETBAG SD WHERE SD.IslemNo=SH.IslemNo or SD.IslemNo=SH.IslemNo3) AND IslemTuru='Depo Vir.')        
--STOKHAR OLUP STOKHARDETBAG OLMAYAN KAYITLARI GÖRMEK İÇİN        
select IslemNo from STOKHAR SH WHERE NOT EXISTS (SELECT * FROM STOKHARDETBAG SD WHERE SD.IslemNo=SH.IslemNo or SD.IslemNo=SH.IslemNo3)        
--STOKHAR OLUP STOKHARDETBAG OLMAYAN KAYITLARI SİLMEK İÇİN        
DELETE FROM STOKHAR WHERE IslemNo IN  (select IslemNo from STOKHAR SH WHERE NOT EXISTS       
(SELECT * FROM STOKHARDETBAG SD WHERE SD.IslemNo=SH.IslemNo or SD.IslemNo=SH.IslemNo3) AND IslemTuru<>'Depo Vir.' )   
  
-- Faturalaşmış Açık Kalan İrsaliyeleri Kapatan Sorgu  
UPDATE sb  SET AcikKapali = 'K' FROM STOKHARDETBAG sb  
 WHERE FisTuru = 'I'     and AcikKapali = 'A'   
  and FaturaNo > 0     and IslemTuru in ('Alış','Alış İade','Satış','Satış İade')  
  
   			
  and EXISTS(select * from STOKHAR sh where sh.IslemNo = sb.IslemNo )  

go--
--------------------------------------------------------------------------------------------------------------------------------------  
     
ALTER TABLE StokFiyat ALTER COLUMN IslemNo int null
go--
------------------------------------------------------------------------------------------------------------------------------------  
if exists (select * from sys.procedures where name='sp_BankaIslemListesi')
drop proc sp_BankaIslemListesi
go--

CREATE   PROCEDURE [dbo].[sp_BankaIslemListesi]                 
 @Tarih1 varchar(30),                
 @Tarih2 varchar(30),                
 @Dep1 varchar(500),                
 @Dep2 varchar(500),                
 @OrderBy int,                
 @Arama varchar(100),                
 @IslemTuru varchar(25),                  
 @GosterilecekKayit int,      
 @IslemNoLike bit = 0,    
 @Departman varchar(20)    
AS                
BEGIN                
  
declare @tstr nvarchar(30);                                            
                                            
if @orderby in (0,4)                                              
  set @tstr='ISLEMNO DESC'                                              
if @orderby=1                                               
 set @tstr='BANKADI DESC,ISLEMNO DESC'                                               
if @orderby=2                                               
 set @tstr='HESAPNO DESC,ISLEMNO DESC'                                              
if @orderby=3                                               
 set @tstr='ACIKLAMA DESC,ISLEMNO DESC'                                               
  
 DECLARE @SQLSTR NVARCHAR(MAX)                
    
 SET @SQLSTR = 'SELECT * FROM (SELECT TOP '+CAST(@GosterilecekKayit as nvarchar(10))+' ROW_NUMBER() OVER (ORDER BY '+@tstr+') AS RowNum,* FROM BANKA WHERE TARIH >='''+ @Tarih1+''' AND TARIH <= '''+@Tarih2+'''';                 
                           
 SET @SQLSTR = @SQLSTR + ' AND (Departman >= '+@dep1+' AND Departman <= '+@dep2+') ';                
              
 IF @IslemTuru <> 'Tümü'                 
  SET @SQLSTR = @SQLSTR + ' AND BAACIKLA = '''+@IslemTuru+'''';           
    
 IF @Departman <> ''                 
  SET @SQLSTR = @SQLSTR + ' AND Departman = '''+@Departman+'''';         
        
if @arama <> ''       
begin            
 if @orderby=0       
 begin      
  if @IslemNoLike = 0      
  set @SQLSTR=@SQLSTR+'and CAST(ISLEMNO as nvarchar(20)) = '''+@arama+''' '       
  else      
  set @SQLSTR=@SQLSTR+'and ISLEMNO like ''%'+@arama+'%'' '       
 end;      
               
  IF @orderby = 1                
   SET @SQLSTR = @SQLSTR + ' AND UPPER(BANKADI) LIKE UPPER(''%'+@arama+'%'') ';                
  IF @orderby = 2                
   SET @SQLSTR = @SQLSTR + ' AND UPPER(HESAPNO) LIKE UPPER(''%'+@arama+'%'') ';                
  IF @orderby = 3                
   SET @SQLSTR = @SQLSTR + ' AND UPPER(ACIKLAMA) LIKE UPPER(''%'+@arama+'%'') ';                
  IF @orderby = 4                
   SET @SQLSTR = @SQLSTR + ' AND ((UPPER(BANKADI) LIKE UPPER(''%'+@arama+'%'')) OR (UPPER(HESAPNO) LIKE UPPER(''%'+@arama+'%'')) OR  
          (UPPER(ACIKLAMA) LIKE UPPER(''%'+@arama+'%'')) OR (UPPER(MUSADI) LIKE UPPER(''%'+@arama+'%'')) OR  
          (UPPER(Aciklama2) LIKE UPPER(''%'+@arama+'%''))) ';         
end;                      
          
SET @SQLSTR = @SQLSTR + ' )x ORDER BY ISLEMNO';  --AND BORC+ALACAK > 0.01                       
                 
EXECUTE sp_executesql  @SQLSTR  
                
END; 
go

if exists (select * from sys.procedures where name='sp_Bakim_Doviz_KdvDH_Update')
drop proc [sp_Bakim_Doviz_KdvDH_Update]

 go

CREATE  PROCEDURE [sp_Bakim_Doviz_KdvDH_Update] 
AS  
BEGIN  
 declare @DovizKod nvarchar(5),@KdvDH nvarchar(1)  
 declare @i int,@sorgu nvarchar(max),@cnt nvarchar(2)   
  
 IF (select count(*) from DOVIZT where DovizKodu = 'YP') > 0   
  SET @DovizKod = 'YP'  
 ELSE IF  (select count(*) from DOVIZT where DovizKodu = 'TL') > 0  
  SET @DovizKod = 'TL'  
 ELSE   
  select TOP 1  @DovizKod = DovizKodu from DOVIZT ORDER BY NoId   
         
 SET @i = 1;          
 WHILE @i <= 20           
 BEGIN          
    SET @cnt = CAST(@i as varchar(2));          
    SET @sorgu = ' UPDATE StokFiyat SET  F'+@cnt+'DovizKodu = ''' + @DovizKod + ''' WHERE  ISNULL(F'+@cnt+'DovizKodu,'''') = '''''                 
    EXEC sp_executesql @sorgu;     
    SET @i += 1;          
 END;          

 UPDATE StokFiyat SET F1Kdv = 'H' WHERE F1Kdv is null or F1Kdv not in ('D','H') 
 UPDATE StokFiyat SET F2Kdv = 'H' WHERE F2Kdv is null or F2Kdv not in ('D','H') 
 UPDATE StokFiyat SET F3Kdv = 'H' WHERE F3Kdv is null or F3Kdv not in ('D','H')  
 UPDATE StokFiyat SET F4Kdv = 'D' WHERE F4Kdv is null or F4Kdv not in ('D','H') 
   
 UPDATE sk SET sk.F1DovizKodu = sf.F1DovizKodu,  sk.F2DovizKodu = sf.F2DovizKodu,    
    sk.F3DovizKodu = sf.F3DovizKodu,     sk.F4DovizKodu = sf.F4DovizKodu,  
	sk.F1Kdv    = sf.F1Kdv,   sk.F2Kdv    = sf.F2Kdv,  
    sk.F3Kdv    = sf.F3Kdv,  sk.F4Kdv    = sf.F4Kdv
  FROM  STOKKARTI sk,StokFiyat sf WHERE sk.Kodu = sf.Kodu        
END;  
go--
-------------------------------------------------------------------------------
if exists (select * from sys.procedures where name='sp_CariGenelBorcAlacak')
drop proc sp_CariGenelBorcAlacak
go--
-------------------------------------------------------------------------------
CREATE   PROC sp_CariGenelBorcAlacak  
(@KullaniciNo int,  
 @AktifPasif int  
 
)  
AS  
BEGIN  
 DECLARE @Sorgu nvarchar(max)  
 DECLARE @AktifPasifSorgu nvarchar(50) = '';  
 DECLARE @Dep nvarchar(500) = (select Deger from KullaniciAyarlari where Ayar = 'KullaniciGöreceği Departmanlar' and KullaniciNo = @KullaniciNo)  
  
 IF @AktifPasif = 0  
   SET @AktifPasifSorgu = ' AND  M.MUSDURUM = ''P'''   
 ELSE  
 IF @AktifPasif = 1  
   SET @AktifPasifSorgu = ' AND  M.MUSDURUM = ''A''';   
  
 SET @Sorgu = ' SELECT M.Tipi, M.Departman, M.MUSDURUM,M.SaticiKodu, M.SaticiAdi,SUM(BORC) AS TOPBORC,SUM(ALACAK) AS TOPALACAK,(SUM(BORC) - SUM(ALACAK))  BAKIYE, '+  
     ' (select DepartmanAdi from Departman d  where (Duzey1 + Duzey2 + Duzey3 + Duzey4) = M.Departman) DepartmanAdi ' +  
     ' FROM ACARI C,AMUSTERI M  WHERE C.MUSNO = M.MUSNO  AND M.Departman  in (' + @Dep +') ' + @AktifPasifSorgu + ' GROUP BY M.Tipi, M.Departman, M.MUSDURUM,M.SaticiKodu,M.SaticiAdi'  
  
  
    
 --print @Sorgu  
   EXECUTE sp_executesql @Sorgu  
END				
go--
ALTER  TABLE AcariTakas alter  column ACIKLAMA [nvarchar](400) NULL
go--
update Parametre set Deger='0' where Param='Görsel Efektler'  				
go--
if not exists (SELECT 1 FROM VTGuncellemeleri WHERE VTVersiyon='7.2.1')
BEGIN
insert into VTGuncellemeleri (VTVersiyon, SonIslemNo, TarihSaat, Prg)
VALUES ('7.2.1',(select ISLEMNO from ADIGSABITLER ),GETDATE(),'OM')
END

go--


ALTER TABLE ASABIT ALTER COLUMN  VERGIDA NVARCHAR(200) NULL      
go--
if exists (select * from sys.procedures where name='sp_lisans_bakim')
drop proc sp_lisans_bakim
go--
CREATE  PROCEDURE sp_lisans_bakim
AS
BEGIN	
	SELECT GETDATE();
END;
go--
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE Name='xFaturaTarihi')
BEGIN
CREATE NONCLUSTERED INDEX [xFaturaTarihi] ON [dbo].[STOKHAR] (	[FaturaTarihi] ASC)
END;
go--

IF NOT EXISTS (SELECT *  FROM sys.columns WHERE  object_id = OBJECT_ID(N'[dbo].[MasrafKrt]') AND name = 'StokNo') 
 BEGIN 
  ALTER TABLE MasrafKrt ADD StokNo int
 END 
ELSE 
 BEGIN 
alter table MasrafKrt ALTER COLUMN StokNo int
 END

go--


if exists (select * from sys.procedures where name='sp_GunlukDurumRaporu')
drop proc sp_GunlukDurumRaporu
go--


create  procedure sp_GunlukDurumRaporu(@Tarih1 DATETIME,@Tarih2 DATETIME,@Tip nvarchar(1),@KulNo nvarchar (5) = null)  
AS
--   sp_GunlukDurumRaporu '2024-04-15 12:00AM','2024-04-29 12:00AM','T'
BEGIN
    DECLARE @SQL nvarchar(max);
	DECLARE @Fiyat nvarchar(30);
    DECLARE @KulNoStr nvarchar(30);  
	select @Fiyat = Deger from  Parametre where Param = 'Günlük Kar Raporu Kullanılacak Fiyat';

	IF (@Fiyat = '') OR (@Fiyat IS NULL)
	BEGIN
		SET @Fiyat = 'StokKartiFiyat1';
	END;


	 IF @KulNo IS NULL
	 BEGIN
		SET @KulNoStr = '';  
	 END
	 ELSE
	 BEGIN
		SET @KulNoStr = ' AND sh.KULNO = ' + @KulNo;  
	 END; 

	IF @Tip = 'T'   ---'Fatura Toplami' Turu,IslemTuru,  '' NakitVisa, 
	BEGIN
	SET @SQL=' select  1 No , ''Fatura Toplami'' Turu, CASE WHEN IslemTuru = ''Prk.Satış'' THEN ''Veresiye Prk.Satış'' ELSE IslemTuru END IslemTuru  ,'''' NakitVisa,      
    sum(Miktar*BirimFiyat*(100+Kdv)/100) IskontosuzTutar, 
    sum(SonTutar-(Miktar*BirimFiyat*(100+Kdv)/100)) IskTop,
    sum(Miktar*BirimFiyat*(100+Kdv)/100) + sum(SonTutar-(Miktar*BirimFiyat*(100+Kdv)/100)) Tutar, 
    SUM((sh.SonTutar + ISNULL(sh.SatMasrafTutari,0)) - (sh.Miktar * sf.'+@Fiyat+')) AS Karlilik
   from STOKHAR  sh
				LEFT JOIN StokFiyatlari sf on sf.StokNo = sh.StokNo
				LEFT JOIN KASA K ON K.ISLEMNO=sh.IslemNo
				where FisTuru=''F'' and IslemTuru in (''Satış'' ,''Alış'' ,''Alış İade'' ,''Satış İade'',''Prk.Satış'') 
				AND  not exists( Select 1 from KASA K where K.ISLEMNO = sh.IslemNo)	
				AND  sh.FaturaTarihi >= ''@Tarih1'' and sh.FaturaTarihi <= ''@Tarih2'''+ @KulNoStr +'
				group by IslemTuru
				UNION ALL	
				SELECT 2,IslemTuru, k.BAACIKLA,NakitVisa,      
 	sum(Miktar*BirimFiyat*(100+Kdv)/100) IskontosuzTutar, 
 	sum(SonTutar-(Miktar*BirimFiyat*(100+Kdv)/100)) IskTop,
 	sum(Miktar*BirimFiyat*(100+Kdv)/100) + sum(SonTutar-(Miktar*BirimFiyat*(100+Kdv)/100)) Tutar, 
 	SUM((sh.SonTutar + ISNULL(sh.SatMasrafTutari,0)) - (sh.Miktar * sf.'+@Fiyat+')) AS Karlilik
				from STOKHAR sh 
				left JOIN KASA k ON k.ISLEMNO = sh.IslemNo
				LEFT JOIN StokFiyatlari sf on sf.StokNo = sh.StokNo
				WHERE  FisTuru=''F'' AND (sh.IslemTuru = ''Prk.Satış'') AND k.BAACIKLA IN (''KK.Tahsilat'',''Tahsilat'')
				 AND  sh.FaturaTarihi >= ''@Tarih1'' and sh.FaturaTarihi <= ''@Tarih2'''+ @KulNoStr +'
				GROUP BY sh.IslemTuru,k.BAACIKLA,NakitVisa 
				UNION ALL 
				select 3,''Diğer Kasa Hareketleri'',BAACIKLA,'''' , SUM(BORC) Tutar,0,0,''''from KASA sh where BAACIKLA IN (''KK.Tahsilat'',''Tahsilat'') 
				and not exists (select 1 from STOKHARDETBAG db where db.IslemNo = sh.ISLEMNO)
				and TARIH >= ''@Tarih1'' and TARIH <= ''@Tarih2'' '+ @KulNoStr +'	
				group by BAACIKLA
				UNION ALL 
				select 4,''Faturalı Kasa Hareketleri'',BAACIKLA,'''', SUM(BORC) Tutar,0,0,''''  from KASA sh where BAACIKLA IN (''KK.Tahsilat'',''Tahsilat'') 
				and exists (select 1 from STOKHARDETBAG db where db.IslemNo = sh.ISLEMNO)
				and TARIH >= ''@Tarih1'' and TARIH <= ''@Tarih2'' '+ @KulNoStr +'	
				group by BAACIKLA
				UNION ALL
				SELECT 5,''Çek -Senet Girişleri'',BAACIKLA,'''',SUM(sh.ALACAK) AS TUTAR,0,0,''''  FROM dbo.ACARI sh 
				WHERE BAACIKLA in(''Çek Girişi'',''Senet Girişi'') and  TARIH >= ''@Tarih1'' and TARIH <= ''@Tarih2'' '+ @KulNoStr +'	
				group by BAACIKLA	
				UNION ALL
				SELECT 6,''Ödeme Islemleri'',BAACIKLA,'''',SUM(sh.BORC) AS TUTAR,0,0,'''' FROM dbo.ACARI sh
				WHERE BAACIKLA = ''Ödeme'' and  TARIH >= ''@Tarih1'' and TARIH <= ''@Tarih2'' '+ @KulNoStr +'	
				group by BAACIKLA order by 1'; 
    END;

	SET @sql =  REPLACE(@Sql,'@Tarih1',@Tarih1)
	SET @sql =  REPLACE(@Sql,'@Tarih2',@Tarih2)		
--	PRINT @SQL
	EXEC sp_executesql  @sql;
END;

go--

 if exists (select * from sys.procedures where name='sp_DovizKurAnaliz')
drop proc sp_DovizKurAnaliz
go--
 CREATE proc sp_DovizKurAnaliz 
as
select   'ACARI' TABLO,DOVIZCINSI,DOVIZKODU,MAX(DovizKur) maxKur,MIN(DovizKur) minKur,(select DovizAdi from DOVIZT where NoId=ACARI.DOVIZCINSI) from ACARI GROUP BY DOVIZCINSI,DOVIZKODU 
union all
select   'KASA',DovizCinsi ,DovizKodu,MAX(DovizKur),MIN(DovizKur),(select DovizAdi from DOVIZT where NoId=KASA.DovizCinsi)  from KASA GROUP BY DovizCinsi ,DovizKodu
union all
select   'STOKHAR',DovizCinsi,DovizKodu ,MAX(DovizKuru ),MIN(DovizKuru),(select DovizAdi from DOVIZT where NoId=STOKHAR.DovizCinsi)  from STOKHAR  GROUP BY DovizCinsi,DovizKodu 
union all
select   'STOKHARDETBAG',DovizCinsi,DovizKodu ,MAX(DovizKur ),MIN(DovizKur ),(select DovizAdi from DOVIZT where NoId=STOKHARDETBAG.DovizCinsi)  from STOKHARDETBAG   GROUP BY DovizCinsi,DovizKodu 
order by 1,3
go--
IF NOT EXISTS (SELECT *  FROM sys.columns WHERE  object_id = OBJECT_ID(N'[dbo].[MasrafKrt]') AND name = 'StokNo') 
 BEGIN 
  ALTER TABLE MasrafKrt ADD StokNo int
 END 
ELSE 
 BEGIN 
alter table MasrafKrt ALTER COLUMN StokNo int
 END

go--


 go--
 if exists (select * from sys.procedures where name='sp_DovizKontrol')
drop proc sp_DovizKontrol
go--
CREATE  PROCEDURE sp_DovizKontrol

AS    
BEGIN    
  
update KASAT set DovizNoId = (select top 1 NoId from DOVIZT order by NoId ) where DovizNoId in (  
select DovizNoId from KASAT where DovizNoId not in (select NoId from DOVIZT ) )  
  
  update t SET t.DovizKodu = d.DovizKodu  from STOKHAR t,DOVIZT  d where t.DovizCinsi = d.NoId ;  
  update t SET t.DovizKodu = d.DovizKodu  from STOKHARDETBAG t,DOVIZT  d where t.DovizCinsi = d.NoId ;  
     update t SET t.DovizKodu = d.DovizKodu ,t.DovizAdi=d.DovizAdi  from KASAT t,DOVIZT  d where t.DovizNoId = d.NoId ;  
  update t SET t.DOVIZKODU = d.DovizKodu  from ACARI t,DOVIZT  d where t.DOVIZCINSI = d.NoId ;  
  update t SET t.DovizKodu = d.DovizKodu ,t.DovizAdi=d.DovizAdi  from HESAPLAR t,DOVIZT  d where t.DovizCinsi = d.NoId ;  
     update t SET t.DovizKodu = d.DovizKodu  from BANKA t,DOVIZT  d where t.DovizCinsi = d.NoId ;  
  update t SET t.DovizKodu = d.DovizKodu  from BORDRO t,DOVIZT  d where t.DovizCinsi = d.NoId ;  
  update t SET t.DovizKodu = d.DovizKodu  from CEK t,DOVIZT  d where t.DovizCinsi = d.NoId ;  
     update t SET t.DOVIZKODU = d.DovizKodu  from GELGID t,DOVIZT  d where t.DOVIZCINSI = d.NoId ;  
  update t SET t.DovizKodu = d.DovizKodu  from KASA t,DOVIZT  d where t.DovizCinsi = d.NoId ;  
  update t SET t.DovizKodu = d.DovizKodu  from SIPARISHAR t,DOVIZT  d where t.DovizCinsi = d.NoId ;  
     update t SET t.DovizKodu = d.DovizKodu  from SIPARISHARDETBAG t,DOVIZT  d where t.DovizCinsi = d.NoId ;  
  update t SET t.DovizKodu = d.DovizKodu  from TEKLIFHAR t,DOVIZT  d where t.DovizCinsi = d.NoId ;  
  update t SET t.DovizKodu = d.DovizKodu  from TEKLIFHARDETBAG t,DOVIZT  d where t.DovizCinsi = d.NoId ;  
     update t SET t.DovizKodu = d.DovizKodu  from Visa t,DOVIZT  d where t.DovizCinsi = d.NoId ;  
  
  select * from (    
  select DovizCinsi, DovizKodu from STOKHAR    
  union    
  select DovizCinsi, DovizKodu from STOKHARDETBAG    
  union    
  select DovizNoId,DovizKodu from KASAT    
  union     
  select DOVIZCINSI,DOVIZKODU from ACARI    
  union    
  select DovizCinsi,DovizKodu from HESAPLAR    
  union    
  select DovizCinsi,DovizKodu from BANKA    
  union    
  select DovizCinsi,DovizKodu from BORDRO    
  union    
  select DovizCinsi,DovizKodu from CEK    
  union    
  select DOVIZCINSI,DOVIZKODU from GELGID    
  union    
  select DovizCinsi,DovizKodu from KASA    
  union    
  select DovizCinsi,DovizKodu from SIPARISHAR    
  union    
  select DovizCinsi,DovizKodu from SIPARISHARDETBAG    
  union    
  select DovizCinsi,DovizKodu from TEKLIFHAR    
  union    
  select DovizCinsi,DovizKodu from TEKLIFHARDETBAG    
  union    
  select DovizCinsi,DovizKodu from Visa    
  union    
  select ka1.Deger,ka2.Deger from KullaniciAyarlari ka1,KullaniciAyarlari ka2    
  where ka1.KullaniciNo = ka2.KullaniciNo    
  and ka1.Ayar = 'VarsayilanDovizId'    
  and ka2.Ayar = 'VarsayilanDovizKodu'    
  ) t where DovizCinsi not in (select NoId from DOVIZT )    
END
-------------------------------------------------------------------------------------------------------------------------------------------
go--
update b set b.AnaBirim=1, b.SiraNo=1 from StokBarkodlari b , STOKKARTI k where b.StokNo=k.StokNo and b.Barkodu=k.Barkodu
go--
update b set b.AnaBirim=0 , b.SiraNo=10 from StokBarkodlari b , STOKKARTI k where b.StokNo=k.StokNo and b.Barkodu<>k.Barkodu
go--
update s1 SET  s1.SiraNo = s2.Rank from StokBarkodlari s1, (select *,DENSE_RANK() OVER  (PARTITION BY StokKodu ORDER BY AnaBirim DESC,Barkodu ) AS Rank  from StokBarkodlari) s2
where s1.StokBarkodlariNoId = s2.StokBarkodlariNoId
go--
update StokBarkodlari set AnaBirim=1 where SiraNo=1
go--
update StokBarkodlari set AnaBirim=0 where SiraNo<>1
go--
 if exists (select * from sys.procedures where name='sp_VTVersiyon')
drop proc sp_VTVersiyon
 
go--
	CREATE  PROCEDURE sp_VTVersiyon 
	AS 
	BEGIN
		 if not exists (select * from dbo.syscolumns where id = object_id(N'VTGuncellemeleri') and name=N'Prg') 
		 begin 
			ALTER TABLE VTGuncellemeleri add Prg NVARCHAR(2) NOT NULL Default('OM') 
		 end

		 SELECT MAX(VTVersiyon) VTVersiyon FROM VTGuncellemeleri Where Prg='OM';
	END;	
	go--

go--
DELETE GridView WHERE KayitIsmi = 'FrmFaturaIslemlericxGrid1cxGrid1DBTableView1'
go--
if exists (select * from sys.procedures where name='sp_FaturaIslemleriListesi')
drop proc sp_FaturaIslemleriListesi
go--
CREATE  PROCEDURE [dbo].[sp_FaturaIslemleriListesi]                                                  
  @tarih1 varchar(20),                                                   
  @tarih2 varchar(20),                                                  
  @dep varchar(500),                                                  
  @orderby int,                                                  
  @arama varchar(100),                                                  
  @GosterilecekKayit int,                                                  
  @IslemTuru varchar(20),                                                  
  @Durumu int,                                      
  @IslemTipi  varchar(30),                          
  @FatSerNo  varchar(3),                          
  @eFaturaNo  varchar(30),                          
  @FaturaTuru varchar(1),              
  @IslemNoLike bit = 0,                
  @TP varchar(2) = 'TF'    
AS                                                  
                      
declare @str nvarchar(max)                                                  
declare @rc int                                                   
declare @tmp table (trc int)                                                  
declare @ayrac varchar(2)                          
declare @peFaturaNo varchar(50)                  
if @eFaturaNo<>''                  
select @peFaturaNo=UPPER(@eFaturaNo)                  
else set @peFaturaNo=''                  
set @ayrac='"';       
      
declare @tstr varchar(100);      
      
if @orderby in (0,8,9)                                                  
  set @tstr='IslemNo DESC'                                                  
if @orderby=1                                                   
 set @tstr='FaturaNo DESC,IslemNo DESC'                                                   
if @orderby=2                                                   
 set @tstr='CariAdi DESC,IslemNo DESC'                                                  
if @orderby=3                                                   
 set @tstr='CariKodu DESC,IslemNo DESC'                                                   
if @orderby=4                                                  
 set @tstr='KULADI DESC,IslemNo DESC'                                                  
if @orderby=5                                                  
 set @tstr='SaticiAdi DESC,IslemNo DESC'                                        
if @orderby=6                                                  
 set @tstr='eFaturaDurumu DESC,IslemNo DESC'                           
 if @orderby=7                                                  
 set @tstr='YaziciCount DESC,IslemNo DESC'                           
                    
set @str='select * from (select TOP ' + CAST(@GosterilecekKayit as nvarchar(10)) + ' ROW_NUMBER() over (order by '+@tstr+') as sira,'''' as plaka,*'+         
            ' from STOKHARDETBAG where FisTuru = ''F'' AND TP = '''+ @TP + ''' AND FaturaTarihi >='''+ @Tarih1+ ''' and FaturaTarihi <= '''+@Tarih2+'''';               
          
if @peFaturaNo<>''                          
set @str=@str+'and upper(eFaturaNo) like upper(''%'+@peFaturaNo+'%'') '             
          
if @FatSerNo<>''                          
set @str=@str+'and Replace(FatSerNo,'''''''','''+@ayrac+''') = '''+@FatSerNo+''' '            
                                             
if @dep <> ''                                                  
 set @str=@str+' and Departman in ('+@Dep+')'                                                  
if @IslemTuru <> 'Tümü'                                                  
 set @str=@str+' and IslemTuru = '''+@IslemTuru+''''                                    
if @IslemTipi <> 'Tümü' and   @IslemTipi <> ''                                                 
 set @str=@str+' and IslemTipi like ''%'+@IslemTipi+'%'''                                        
              
if @arama <> ''               
begin              
if @orderby=0               
begin              
 if @IslemNoLike = 0              
 set @str=@str+'and CAST(IslemNo as nvarchar(20)) = '''+@arama+''' '               
 else              
 set @str=@str+'and IslemNo like ''%'+@arama+'%'' '               
end;                                                
if @orderby=1                                                   
 set @str=@str+'and upper(FaturaNo) like upper('''+@arama+'%'') '                                                   
if @orderby=2                                                   
 set @str=@str+'and upper(CariAdi) like upper(''%'+@arama+'%'') '                                                  
if @orderby=3                                                   
 set @str=@str+'and upper(CariKodu) like upper('''+@arama+'%'') '                                                   
if @orderby=4                                                  
 set @str=@str+'and upper(KULADI) like upper(''%'+@arama+'%'') '                                                  
if @orderby=5                                                  
 set @str=@str+'and upper(SaticiAdi) like upper(''%'+@arama+'%'') '                                       
 if @orderby=6                                                  
 set @str=@str+'and upper(eFaturaDurumu) like upper(''%'+@arama+'%'') '                                       
if @orderby=7                                                  
 set @str=@str+'and upper(YaziciCount) like upper(''%'+@arama+'%'') '                                       
if @orderby=8                                                  
 set @str=@str+'and upper(FaturaTarihi) like upper(''%'+@arama+'%'') '                     
if @orderby=9                                                  
 set @str=@str+'and ((upper(Ack1) like upper(''%'+@arama+'%'')) or (upper(Ack2) like upper(''%'+@arama+'%'')) or (upper(Ack3) like upper(''%'+@arama+'%'')) or (upper(Ack4) like upper(''%'+@arama+'%''))             
   or EXISTS (Select 1 from ACARI AC where AC.ISLEMNO = IslemNo and upper(Aciklama2) like upper(''%'+@arama+'%''))            
      or EXISTS (Select 1 from ACIKLAMA AC where AC.FATURANO = IslemNo and upper(TeslimEden) like upper(''%'+@arama+'%''))            
      or EXISTS (Select 1 from ACIKLAMA AC where AC.FATURANO = IslemNo and upper(TeslimAlan) like upper(''%'+@arama+'%''))) '               
end;                                              
set @str=@str+')tbl ORDER BY IslemNo';                                                                    
                                                                   
--print @str      
  
execute sp_executesql  @str  
go-- 
update StokBarkodlari set AnaBirim=0 where Carpani<>1
go--
 
UPDATE Parametre SET Deger=	500 WHERE Param='Bilgi Gönderme BeklemeSüresi'
go--
IF EXISTS (    SELECT 1    FROM sys.columns    WHERE object_id = OBJECT_ID('dbo.ISOBIRIM')     AND name = 'ISOId')
BEGIN
    EXEC sp_rename 'ISOBIRIM.ISOId', 'Id', 'COLUMN';
END
go--
IF EXISTS (    SELECT 1    FROM sys.columns    WHERE object_id = OBJECT_ID('dbo.Kullanicilar')    AND name = 'IYTED')
BEGIN
    ALTER TABLE Kullanicilar DROP COLUMN IYTED;
END
go--

IF EXISTS (    SELECT 1    FROM sys.columns    WHERE object_id = OBJECT_ID('dbo.Kullanicilar')    AND name = 'IYTSD')
BEGIN
    ALTER TABLE Kullanicilar DROP COLUMN IYTSD;
END
go--
  declare @CNTNAME NVARCHAR(100),@SQL NVARCHAR(MAX)
select @CNTNAME=name from sys.default_constraints where name like 'DF%Kullanicilar_Departman%'
SET @SQL='ALTER TABLE [dbo].[Kullanicilar] DROP CONSTRAINT ['+ CONVERT(VARCHAR(100),@CNTNAME)+']'
EXEC(@SQL)
go-- 
    ALTER TABLE Kullanicilar ADD CONSTRAINT DF_Kullanicilar_Departman DEFAULT (('01000000')) FOR Departman;

go--

declare @CNTNAME NVARCHAR(100),@SQL NVARCHAR(MAX)
select @CNTNAME=name from sys.default_constraints where name like '%Kullan%Depar%'
SET @SQL='ALTER TABLE [dbo].[Kullanicilar] DROP CONSTRAINT ['+ CONVERT(VARCHAR(100),@CNTNAME)+']'
EXEC(@SQL)
go--
ALTER TABLE ASABIT ALTER COLUMN  VERGIDA NVARCHAR(200) NULL	
go--
if not exists (SELECT 1 FROM VTGuncellemeleri WHERE VTVersiyon='7.2.2')
BEGIN
insert into VTGuncellemeleri (VTVersiyon, SonIslemNo, TarihSaat, Prg)
VALUES ('7.2.2',(select ISLEMNO from ADIGSABITLER ),GETDATE(),'OM')
END
go--

select top 5 * from VTGuncellemeleri order by VTVersiyon desc
go--   				  

DELETE GridView WHERE KayitIsmi = 'FrmFaturaIslemlericxGrid1cxGrid1DBTableView1'
go-- 
if exists (select * from sys.procedures where name='sp_FaturaIslemleriListesi')
drop proc sp_FaturaIslemleriListesi
go--
CREATE PROCEDURE [dbo].[sp_FaturaIslemleriListesi]                                                  
  @tarih1 varchar(20),                                                   
  @tarih2 varchar(20),                                                  
  @dep varchar(500),                                                  
  @orderby int,                                                  
  @arama varchar(100),                                                  
  @GosterilecekKayit int,                                                  
  @IslemTuru varchar(20),                                                  
  @Durumu int,                                      
  @IslemTipi  varchar(30),                          
  @FatSerNo  varchar(3),                          
  @eFaturaNo  varchar(30),                          
  @FaturaTuru varchar(1),              
  @IslemNoLike bit = 0,                
  @TP varchar(2) = 'TF'    
AS                                                  
                      
declare @str nvarchar(max)                                                  
declare @rc int                                                   
declare @tmp table (trc int)                                                  
declare @ayrac varchar(2)                          
declare @peFaturaNo varchar(50)                  
if @eFaturaNo<>''                  
select @peFaturaNo=UPPER(@eFaturaNo)                  
else set @peFaturaNo=''                  
set @ayrac='"';       
      
declare @tstr varchar(100);      
      
if @orderby in (0,8,9)                                                  
  set @tstr='IslemNo DESC'                                                  
if @orderby=1                                                   
 set @tstr='FaturaNo DESC,IslemNo DESC'                                                   
if @orderby=2                                                   
 set @tstr='CariAdi DESC,IslemNo DESC'                                                  
if @orderby=3                                                   
 set @tstr='CariKodu DESC,IslemNo DESC'                                                   
if @orderby=4                                                  
 set @tstr='KULADI DESC,IslemNo DESC'                                                  
if @orderby=5                                                  
 set @tstr='SaticiAdi DESC,IslemNo DESC'                                        
if @orderby=6                                                  
 set @tstr='eFaturaDurumu DESC,IslemNo DESC'                           
 if @orderby=7                                                  
 set @tstr='YaziciCount DESC,IslemNo DESC'                           
                    
set @str='select * from (select TOP ' + CAST(@GosterilecekKayit as nvarchar(10)) + ' ROW_NUMBER() over (order by '+@tstr+') as sira,'''' as plaka,*'+         
            ' from STOKHARDETBAG where FisTuru = ''F'' AND TP = '''+ @TP + ''' AND FaturaTarihi >='''+ @Tarih1+ ''' and FaturaTarihi <= '''+@Tarih2+'''';               
          
if @peFaturaNo<>''                          
set @str=@str+'and upper(eFaturaNo) like upper(''%'+@peFaturaNo+'%'') '             
          
if @FatSerNo<>''                          
set @str=@str+'and Replace(FatSerNo,'''''''','''+@ayrac+''') = '''+@FatSerNo+''' '            
                                             
if @dep <> ''                                                  
 set @str=@str+' and Departman in ('+@Dep+')'                                                  
if @IslemTuru <> 'Tümü'                                                  
 set @str=@str+' and IslemTuru = '''+@IslemTuru+''''                                    
if @IslemTipi <> 'Tümü' and   @IslemTipi <> ''                                                 
 set @str=@str+' and IslemTipi like ''%'+@IslemTipi+'%'''                                        
              
if @arama <> ''               
begin              
if @orderby=0               
begin              
 if @IslemNoLike = 0              
 set @str=@str+'and CAST(IslemNo as nvarchar(20)) = '''+@arama+''' '               
 else              
 set @str=@str+'and IslemNo like ''%'+@arama+'%'' '               
end;                                                
if @orderby=1                                                   
 set @str=@str+'and upper(FaturaNo) like upper('''+@arama+'%'') '                                                   
if @orderby=2                                                   
 set @str=@str+'and upper(CariAdi) like upper(''%'+@arama+'%'') '                                                  
if @orderby=3                                                   
 set @str=@str+'and upper(CariKodu) like upper('''+@arama+'%'') '                                                   
if @orderby=4                                                  
 set @str=@str+'and upper(KULADI) like upper(''%'+@arama+'%'') '                                                  
if @orderby=5                                                  
 set @str=@str+'and upper(SaticiAdi) like upper(''%'+@arama+'%'') '                                       
 if @orderby=6                                                  
 set @str=@str+'and upper(eFaturaDurumu) like upper(''%'+@arama+'%'') '                                       
if @orderby=7                                                  
 set @str=@str+'and upper(YaziciCount) like upper(''%'+@arama+'%'') '                                       
if @orderby=8                                                  
 set @str=@str+'and upper(FaturaTarihi) like upper(''%'+@arama+'%'') '                     
if @orderby=9                                                  
 set @str=@str+'and ((upper(Ack1) like upper(''%'+@arama+'%'')) or (upper(Ack2) like upper(''%'+@arama+'%'')) or (upper(Ack3) like upper(''%'+@arama+'%'')) or (upper(Ack4) like upper(''%'+@arama+'%''))             
   or EXISTS (Select 1 from ACARI AC where AC.ISLEMNO = IslemNo and upper(Aciklama2) like upper(''%'+@arama+'%''))            
      or EXISTS (Select 1 from ACIKLAMA AC where AC.FATURANO = IslemNo and upper(TeslimEden) like upper(''%'+@arama+'%''))            
      or EXISTS (Select 1 from ACIKLAMA AC where AC.FATURANO = IslemNo and upper(TeslimAlan) like upper(''%'+@arama+'%''))) '               
end;                                              
set @str=@str+')tbl ORDER BY IslemNo';                                                                    
                                                                   
--print @str      
  
execute sp_executesql  @str 
go-- 
if exists (select * from sys.procedures where name='sp_DepartmanKayitGoster')
drop proc sp_DepartmanKayitGoster
go--
CREATE PROCEDURE sp_DepartmanKayitGoster
AS
BEGIN
	declare @Sorgu nvarchar(max);
	declare @tablename nvarchar(50)
	declare csr_dep cursor for 	
		SELECT t.name
		  FROM sys.tables t,
			   sys.columns c
		 WHERE t.object_id = c.object_id
		   AND c.name = 'Departman';
	SET @Sorgu = '';
	open csr_dep
	fetch next from csr_dep into @tablename
	while @@FETCH_STATUS = 0
	begin			
		IF @Sorgu = ''
			SET @Sorgu = ' Select '''+@tablename+''' as TabloAdi,Departman,count(*) KayitSayisi from ' + @tablename + ' GROUP BY Departman';
		ELSE
			SET @Sorgu = @Sorgu + ' UNION ALL Select '''+@tablename+''' as TabloAdi,Departman,count(*) KayitSayisi from ' + @tablename + ' GROUP BY Departman';	
			
	fetch next from csr_dep into @tablename
	end
	close csr_dep
	deallocate csr_dep
	EXEC sp_executesql @Sorgu;  
END;
go-- 
--exec sp_DepartmanKayitGoster
go-- 

UPDATE Parametre SET Deger=	500 WHERE Param='Bilgi Gönderme BeklemeSüresi'
go-- 
IF EXISTS (    SELECT 1    FROM sys.columns    WHERE object_id = OBJECT_ID('dbo.ISOBIRIM')    AND name = 'ISOId')
BEGIN
EXEC sp_rename 'ISOBIRIM.ISOId'  ,'Id' , 'COLUMN'
end;
 

go-- 
if exists (select * from sys.procedures where name='sp_DovizliTakip')
drop proc sp_DovizliTakip
go--
CREATE  PROCEDURE  sp_DovizliTakip (@DovizKodu nvarchar(2),@DovizliTakip bit = 0,@DovizKur float = 1)
AS
BEGIN
	--exec sp_DovizliTakip 'TL'
	Declare @NoId int
	declare @DovizAdi nvarchar(20)

	Select @NoId = NoId,@DovizAdi = DovizAdi from DOVIZT where DovizKodu = @DovizKodu;

	IF @DovizliTakip = 0 
	BEGIN
		/*UPDATE STOKHAR SET DovizCinsi = @NoId,DovizKodu = @DovizKodu,DovizAlacak = A  
		--select DovizCinsi, DovizKodu,DovizAlacak,DovizBorc,DovizKur,DovizTut,DovizTutB from STOKHARDETBAG  
		  select DovizCinsi,DovizKodu from SIPARISHAR    
		  union    
		  select DovizCinsi,DovizKodu from SIPARISHARDETBAG    
		  union    
		  select DovizCinsi,DovizKodu from TEKLIFHAR    
		  union    
		  select DovizCinsi,DovizKodu from TEKLIFHARDETBAG  */
		UPDATE KASAT SET  DovizNoId = @NoId,DovizKodu = @DovizKodu,DovizAdi = @DovizAdi;
		UPDATE ACARI SET  DOVIZCINSI = @NoId,DOVIZKODU = @DovizKodu,DOVIZTUT = BORC + ALACAK,DovizAlacak = ALACAK,DovizBorc = BORC,DovizKur = @DovizKur;
		UPDATE HESAPLAR SET  DovizCinsi = @NoId,DovizKodu = @DovizKodu,DovizAdi = @DovizAdi;
		UPDATE BANKA SET  DovizCinsi = @NoId,DovizKodu = @DovizKodu,DovizBorc = BORC, DovizAlacak = ALACAK, DovizTut = BORC + ALACAK;
		UPDATE BORDRO SET  DovizCinsi = @NoId,DovizKodu = @DovizKodu,DovizBorc = TUTAR;
		UPDATE CEK SET  DovizCinsi = @NoId,DovizKodu = @DovizKodu,DovizBorc = TUTAR,CekParaBirimi = @DovizKodu;
	    UPDATE GELGID SET  DOVIZCINSI = @NoId,DOVIZKODU = @DovizKodu,DOVIZTUT = BORC + ALACAK,DovizAlacak = ALACAK,DovizBorc = BORC,DovizKuru = @DovizKur;
		UPDATE KASA SET  DovizCinsi = @NoId,DovizKodu = @DovizKodu,DovizBorc = BORC, DovizAlacak = ALACAK, DovizTut = BORC + ALACAK,DovizKur = @DovizKur;
		UPDATE Visa SET  DovizCinsi = @NoId,DovizKodu = @DovizKodu,DovizTut = BORC + ALACAK;
	    UPDATE KullaniciAyarlari SET Deger = @DovizAdi where Ayar = 'VarsayilanDovizAdi';
		UPDATE KullaniciAyarlari SET Deger = @NoId where Ayar = 'VarsayilanDovizId';
		UPDATE KullaniciAyarlari SET Deger = @DovizKodu where Ayar = 'VarsayilanDovizKodu';
	END;
END;   
go--
if exists (select * from sys.procedures where name='sp_Grup_Bakim')
drop proc sp_Grup_Bakim
go--
CREATE  PROCEDURE sp_Grup_Bakim      
AS        
BEGIN   
 -- UreticiFirma Adı insert  STOKKARTI
 INSERT INTO GRUP (GrupAdi,Turu,KULNO,KULADI)        
 select DISTINCT UreticiFirmaKodu,'U',1,'Admin' from STOKKARTI         
 where UreticiFirmaKodu <> '' and UreticiFirmaKodu is not null        
   and NOT EXISTS (Select 1 from GRUP where GrupAdi = UreticiFirmaKodu and Turu = 'U')        
        
   -- Grup Adı insert   STOKKARTI     
 INSERT INTO GRUP (GrupAdi,Turu,KULNO,KULADI)        
 select DISTINCT GrupAdi,'G',1,'Admin' from STOKKARTI sk        
 where GrupAdi <> '' and GrupAdi is not null        
   and NOT EXISTS (Select 1 from GRUP g where g.GrupAdi = sk.GrupAdi and g.Turu = 'G')        
  
  -- Web Grup Adı insert   STOKKARTI     
 INSERT INTO GRUP (GrupAdi,Turu,KULNO,KULADI)        
 select DISTINCT GrupAdi,'W',1,'Admin' from STOKKARTI sk        
 where GrupAdi <> '' and GrupAdi is not null        
   and NOT EXISTS (Select 1 from GRUP g where g.GrupAdi = sk.GrupAdi and g.Turu = 'W')        
 
   --Alt1 Grup Adı insert   STOKKARTI     
 INSERT INTO GRUP (GrupAdi,Turu,KULNO,KULADI)        
 select DISTINCT AltGrupAdi,'48',1,'Admin' from STOKKARTI sk        
 where GrupAdi <> '' and GrupAdi is not null        
   and NOT EXISTS (Select 1 from GRUP g where g.GrupAdi = sk.GrupAdi and g.Turu = '48')        
 
    --Alt2 Grup Adı insert   STOKKARTI     
 INSERT INTO GRUP (GrupAdi,Turu,KULNO,KULADI)        
 select DISTINCT AltGrupAdi2,'49',1,'Admin' from STOKKARTI sk        
 where GrupAdi <> '' and GrupAdi is not null        
   and NOT EXISTS (Select 1 from GRUP g where g.GrupAdi = sk.GrupAdi and g.Turu = '49')        
 
 -- Cari Tip İnsert        
 INSERT INTO GRUP (GrupAdi,Turu,KULNO,KULADI)        
 select DISTINCT Tipi,'T',1,'Admin' from AMUSTERI m        
 where Tipi <> '' and Tipi is not null        
   and NOT EXISTS (Select 1 from GRUP g where g.GrupAdi = m.Tipi and g.Turu = 'T')        
        
 -- Cari O1 İnsert        
 INSERT INTO GRUP (GrupAdi,Turu,KULNO,KULADI)        
 select DISTINCT OZELKOD1,'O1',1,'Admin' from AMUSTERI m        
 where OZELKOD1 <> '' and OZELKOD1 is not null        
   and NOT EXISTS (Select 1 from GRUP g where g.GrupAdi = m.OZELKOD1 and g.Turu = 'O1')        
        
 -- Cari O2 İnsert        
 INSERT INTO GRUP (GrupAdi,Turu,KULNO,KULADI)        
 select DISTINCT OZELKOD2,'O2',1,'Admin' from AMUSTERI m        
 where OZELKOD2 <> '' and OZELKOD2 is not null        
   and NOT EXISTS (Select 1 from GRUP g where g.GrupAdi = m.OZELKOD2 and g.Turu = 'O2')        
        
 -- Cari O3 İnsert        
 INSERT INTO GRUP (GrupAdi,Turu,KULNO,KULADI)        
 select DISTINCT OZELKOD3,'O3',1,'Admin' from AMUSTERI m        
 where OZELKOD3 <> '' and OZELKOD3 is not null        
   and NOT EXISTS (Select 1 from GRUP g where g.GrupAdi = m.OZELKOD3 and g.Turu = 'O3')        
        
 -- Cari O4 İnsert        
 INSERT INTO GRUP (GrupAdi,Turu,KULNO,KULADI)        
 select DISTINCT OZELKOD4,'O4',1,'Admin' from AMUSTERI m        
 where OZELKOD4 <> '' and OZELKOD4 is not null        
   and NOT EXISTS (Select 1 from GRUP g where g.GrupAdi = m.OZELKOD4 and g.Turu = 'O4')        
        
END;  

go-- 
if exists (select * from sys.procedures where name='sp_Stok_Kart_Barkod_Fiyat_Const_DltIns')
drop proc sp_Stok_Kart_Barkod_Fiyat_Const_DltIns
go--

create proc sp_Stok_Kart_Barkod_Fiyat_Const_DltIns   
as   
DECLARE 
    @CNTNAME NVARCHAR(100),
    @TBLNAME NVARCHAR(100),
    @SQL NVARCHAR(MAX);

IF OBJECT_ID('tempdb..##UQConst_Liste') IS NULL
BEGIN
    CREATE TABLE ##UQConst_Liste
    (
        sorgu       NVARCHAR(MAX) NULL,
        Update_Date DATETIME
    );
END;

DECLARE UQ_CURSOR CURSOR FAST_FORWARD FOR
SELECT 
    K.name AS CONST_ADI,
    T.name AS TABLO_ADI
FROM sys.key_constraints K
INNER JOIN sys.tables T 
    ON T.object_id = K.parent_object_id
WHERE K.type = 'UQ'
  AND T.name IN ('STOKKARTI', 'StokBarkodlari', 'StokFiyat')
  AND K.name <> 'STK_UQN';

OPEN UQ_CURSOR;

FETCH NEXT FROM UQ_CURSOR INTO @CNTNAME, @TBLNAME;

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT '--- ' + @CNTNAME + ' --- ' + @TBLNAME;

    SET @SQL = N'ALTER TABLE [dbo].[' + @TBLNAME + N'] DROP CONSTRAINT [' + @CNTNAME + N']';

    PRINT @SQL;
    EXEC sp_executesql @SQL;

    INSERT INTO ##UQConst_Liste (sorgu, Update_Date)
    VALUES (@SQL, GETDATE());

    FETCH NEXT FROM UQ_CURSOR INTO @CNTNAME, @TBLNAME;
END;

CLOSE UQ_CURSOR;
DEALLOCATE UQ_CURSOR;
go
-- drop table ##UQConst_Liste
go-- 
exec  sp_Stok_Kart_Barkod_Fiyat_Const_DltIns
go-- 
--  select * from sys.key_constraints where type ='UQ'
--  SELECT T.name TABLO_ADI ,K.name CONST_ADI,K.type  FROM sys.key_constraints K ,sys.tables T where T.object_id=K.parent_object_id AND K.type='UQ'  
--	WHERE TABLO_ADI IN ('STOKKARTI','StokBarkodlari','StokFiyat') -- and CONST_ADI<> 'STK_UQN'
---- UNIQUE CONST STOKKARTLARI

 ALTER TABLE [dbo].[STOKKARTI] ADD  CONSTRAINT [UQSTK_KOD] UNIQUE NONCLUSTERED ([Kodu] ASC)  WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
go-- 
ALTER TABLE [dbo].[STOKKARTI] ADD  CONSTRAINT [UQSTK_StokNo] UNIQUE NONCLUSTERED ([StokNo] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
go-- 
ALTER TABLE [dbo].[STOKKARTI] ADD  CONSTRAINT [UQSTK_BARKOD] UNIQUE NONCLUSTERED ([Barkodu] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
go-- 
ALTER TABLE [dbo].[StokFiyat] ADD  CONSTRAINT [UQ_STKFyt_KOD] UNIQUE NONCLUSTERED ([Kodu] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
go-- 
ALTER TABLE [dbo].[StokFiyat] ADD  CONSTRAINT [UQ_STKFyt_StokNo] UNIQUE NONCLUSTERED ([StokNo] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
go-- 
ALTER TABLE [dbo].[StokBarkodlari] ADD  CONSTRAINT [UQ_STKBrk_Barkodu] UNIQUE NONCLUSTERED ([Barkodu] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]

--   select * from sys.key_constraints where type ='UQ'
-- SELECT T.name TABLO_ADI ,K.name CONST_ADI,K.type  FROM sys.key_constraints K ,sys.tables T where T.object_id=K.parent_object_id AND K.type='UQ'  
--	WHERE TABLO_ADI IN ('STOKKARTI','StokBarkodlari','StokFiyat') -- and CONST_ADI<> 'STK_UQN'
go-- 
UPDATE STOKKARTI    SET Departman = (Select Deger from KullaniciAyarlari where KullaniciNo = 1 and Ayar = 'VarsayilanDepartmanDuzeyi') 
 WHERE ISNULL(Departman,'x') = 'x'
go-- 
 UPDATE  sk     SET StokAdedi = (SELECT ISNULL(SUM(Miktar), 0) from STOKHAR 
				      WHERE StokKodu = sk.Kodu and GC='G' and FisTuru<>'İ')-
					(SELECT ISNULL(SUM(Miktar), 0) from STOKHAR 
					  WHERE StokKodu = sk.Kodu and GC='C' and FisTuru<>'İ') 
	FROM STOKKARTI sk
   WHERE sk.StokTipi in ('+ Ürün','+ Ambalaj','+ Demirbaş')
     AND StokAdedi is null
go-- 
declare @CNTNAME NVARCHAR(100),@SQL NVARCHAR(MAX)
select @CNTNAME=name from sys.default_constraints where name like '%DF%STOKKA%StokAde%'
SET @SQL='ALTER TABLE [dbo].[STOKKARTI] DROP CONSTRAINT ['+ CONVERT(VARCHAR(100),@CNTNAME)+']'
EXEC (@SQL)
go--
ALTER TABLE [dbo].[STOKKARTI] ADD  CONSTRAINT [DF_STOKKARTI_StokAdedi]  DEFAULT ((0)) FOR [StokAdedi]
go-- 
 IF  EXISTS (SELECT *  FROM sys.triggers WHERE  name='StokFiyat_StokNo')
 BEGIN 
 drop trigger StokFiyat_StokNo
end; 
go-- 
create   trigger StokFiyat_StokNo on StokFiyat  AFTER INSERT    
as      
begin      
 Declare @Kodu nvarchar(30)   
select @Kodu = Kodu from inserted    
--select @Kodu = Kodu from deleted    

update StokFiyat set StokNo=(select top 1  StokNo from STOKKARTI where Kodu=StokFiyat.Kodu ) where  Kodu=@Kodu
update StokBarkodlari set StokNo=(select top 1  StokNo from STOKKARTI where Kodu=StokBarkodlari.StokKodu ) where  StokKodu=@Kodu
end;   
go-- 

ENABLE TRIGGER StokFiyat_StokNo on StokFiyat
go-- 
update StokBarkodlari set AnaBirim=0 where Carpani<>1
go-- 
if exists (select * from sys.procedures where name='sp_GunlukDurumRaporu')
drop proc sp_GunlukDurumRaporu
go-- 
 create   procedure [dbo].[sp_GunlukDurumRaporu](@Tarih1 DATETIME,@Tarih2 DATETIME,@Tip nvarchar(1),@KulNo nvarchar (5) = null)  
AS
--   sp_GunlukDurumRaporu '20240404','20240505','T'
BEGIN
    DECLARE @SQL nvarchar(max);
	DECLARE @Fiyat nvarchar(30);
    DECLARE @KulNoStr nvarchar(30);  
	select @Fiyat = Deger from  Parametre where Param = 'Günlük Kar Raporu Kullanılacak Fiyat';

	IF (@Fiyat = '') OR (@Fiyat IS NULL)
	BEGIN
		SET @Fiyat = 'StokKartiFiyat1';
	END;


 IF @KulNo IS NULL
	 BEGIN
		SET @KulNoStr = '';  
	 END
	 ELSE
	 BEGIN
		SET @KulNoStr = ' AND sh.KULNO = ' + @KulNo;  
	 END; 

IF @Tip = 'T'   ---'Fatura Toplami' Turu,IslemTuru,  '' NakitVisa, 
	BEGIN
	SET @SQL=' select  1 No , ''Fatura Toplami'' Turu, CASE WHEN IslemTuru = ''Prk.Satış'' THEN ''Veresiye Prk.Satış'' ELSE IslemTuru END IslemTuru  ,'''' NakitVisa,      
					   sum(Miktar*BirimFiyat*(100+Kdv)/100) IskontosuzTutar, 
					   sum(SonTutar-(Miktar*BirimFiyat*(100+Kdv)/100)) IskTop,
					   sum(Miktar*BirimFiyat*(100+Kdv)/100) + sum(SonTutar-(Miktar*BirimFiyat*(100+Kdv)/100)) Tutar, 
					   SUM((sh.SonTutar + ISNULL(sh.SatMasrafTutari,0)) - (sh.Miktar * sf.'+@Fiyat+')) AS Karlilik
					  from STOKHAR  sh
				LEFT JOIN StokFiyatlari sf on sf.StokNo = sh.StokNo
				LEFT JOIN KASA K ON K.ISLEMNO=sh.IslemNo
				where FisTuru=''F'' and IslemTuru in (''Satış'' ,''Alış'' ,''Alış İade'' ,''Satış İade'',''Prk.Satış'') 
				AND  not exists( Select 1 from KASA K where K.ISLEMNO = sh.IslemNo)	
				AND  sh.FaturaTarihi >= ''@Tarih1'' and sh.FaturaTarihi <= ''@Tarih2'''+ @KulNoStr +'
				group by IslemTuru
				UNION ALL	
				SELECT 2,IslemTuru, k.BAACIKLA,NakitVisa,      
						sum(Miktar*BirimFiyat*(100+Kdv)/100) IskontosuzTutar, 
						sum(SonTutar-(Miktar*BirimFiyat*(100+Kdv)/100)) IskTop,
						sum(Miktar*BirimFiyat*(100+Kdv)/100) + sum(SonTutar-(Miktar*BirimFiyat*(100+Kdv)/100)) Tutar, 
						SUM((sh.SonTutar + ISNULL(sh.SatMasrafTutari,0)) - (sh.Miktar * sf.'+@Fiyat+')) AS Karlilik
				from STOKHAR sh 
				left JOIN KASA k ON k.ISLEMNO = sh.IslemNo
				LEFT JOIN StokFiyatlari sf on sf.StokNo = sh.StokNo
				WHERE  FisTuru=''F'' AND (sh.IslemTuru = ''Prk.Satış'') AND k.BAACIKLA IN (''KK.Tahsilat'',''Tahsilat'')
				 AND  sh.FaturaTarihi >= ''@Tarih1'' and sh.FaturaTarihi <= ''@Tarih2'''+ @KulNoStr +'
				GROUP BY sh.IslemTuru,k.BAACIKLA,NakitVisa 
				UNION ALL 
				select 3,''Diğer Kasa Hareketleri'',BAACIKLA,'''' , SUM(BORC) Tutar,0,0,''''from KASA sh where BAACIKLA IN (''KK.Tahsilat'',''Tahsilat'') 
				and not exists (select 1 from STOKHARDETBAG db where db.IslemNo = sh.ISLEMNO)
				and TARIH >= ''@Tarih1'' and TARIH <= ''@Tarih2'' '+ @KulNoStr +'	
				group by BAACIKLA
				UNION ALL 
				select 4,''Faturalı Kasa Hareketleri'',BAACIKLA,'''', SUM(BORC) Tutar,0,0,''''  from KASA sh where BAACIKLA IN (''KK.Tahsilat'',''Tahsilat'') 
				and exists (select 1 from STOKHARDETBAG db where db.IslemNo = sh.ISLEMNO)
				and TARIH >= ''@Tarih1'' and TARIH <= ''@Tarih2'' '+ @KulNoStr +'	
				group by BAACIKLA
				UNION ALL
				SELECT 5,''Çek -Senet Girişleri'',BAACIKLA,'''',SUM(sh.ALACAK) AS TUTAR,0,0,''''  FROM dbo.ACARI sh 
				WHERE BAACIKLA in(''Çek Girişi'',''Senet Girişi'') and  TARIH >= ''@Tarih1'' and TARIH <= ''@Tarih2'' '+ @KulNoStr +'	
				group by BAACIKLA	
				UNION ALL
				SELECT 6,''Ödeme Islemleri'',BAACIKLA,'''',SUM(sh.BORC) AS TUTAR,0,0,'''' FROM dbo.ACARI sh
				WHERE BAACIKLA = ''Ödeme'' and  TARIH >= ''@Tarih1'' and TARIH <= ''@Tarih2'' '+ @KulNoStr +'	
				group by BAACIKLA order by 1'; 
    END
	ELSE IF @Tip = 'D'
	BEGIN
	SET @SQL=' select  IslemNo,m.MUSKOD,m.MUSADI,sh.StokKodu,ISNULL(sk.StokAdi,sh.StokAdi) StokAdi,SUM(sh.SonTutar/sh.Miktar) NetFiyat,SUM(sh.Miktar) Miktar,
					  ''Fatura Toplami'' Turu, CASE WHEN IslemTuru = ''Prk.Satış'' THEN ''Veresiye Prk.Satış'' ELSE IslemTuru END IslemTuru  ,'''' NakitVisa,      
					   sum(Miktar*BirimFiyat*(100+Kdv)/100) IskontosuzTutar, 
					   sum(SonTutar-(Miktar*BirimFiyat*(100+Kdv)/100)) IskTop,
					   sum(Miktar*BirimFiyat*(100+Kdv)/100) + sum(SonTutar-(Miktar*BirimFiyat*(100+Kdv)/100)) Tutar, 
					   SUM((sh.SonTutar + ISNULL(sh.SatMasrafTutari,0)) - (sh.Miktar * sf.'+@Fiyat+')) AS Karlilik
					  from STOKHAR  sh
				LEFT JOIN STOKKARTI sk on sk.Kodu = sh.StokKodu
				LEFT JOIN AMUSTERI m on m.MUSNO = sh.CariNo
				LEFT JOIN StokFiyatlari sf on sf.StokNo = sh.StokNo
				LEFT JOIN KASA K ON K.ISLEMNO=sh.IslemNo
				where FisTuru=''F'' and IslemTuru in (''Satış'' ,''Alış'' ,''Alış İade'' ,''Satış İade'',''Prk.Satış'') 
				AND  not exists( Select 1 from KASA K where K.ISLEMNO = sh.IslemNo)	
				AND  sh.FaturaTarihi >= ''@Tarih1'' and sh.FaturaTarihi <= ''@Tarih2'''+ @KulNoStr +'
				group by IslemNo,IslemTuru,m.MUSADI,m.MUSKOD,sh.StokKodu,sk.StokAdi,sh.StokAdi
				UNION ALL	
				SELECT  IslemNo,m.MUSKOD,m.MUSADI,sh.StokKodu,ISNULL(sk.StokAdi,sh.StokAdi) StokAdi,
						SUM(sh.SonTutar/sh.Miktar) NetFiyat,
						SUM(sh.Miktar) Miktar,
						IslemTuru, k.BAACIKLA,NakitVisa,      
						sum(Miktar*BirimFiyat*(100+Kdv)/100) IskontosuzTutar, 
						sum(SonTutar-(Miktar*BirimFiyat*(100+Kdv)/100)) IskTop,
						sum(Miktar*BirimFiyat*(100+Kdv)/100) + sum(SonTutar-(Miktar*BirimFiyat*(100+Kdv)/100)) Tutar, 
						SUM((sh.SonTutar + ISNULL(sh.SatMasrafTutari,0)) - (sh.Miktar * sf.'+@Fiyat+')) AS Karlilik
				from STOKHAR sh 
				LEFT JOIN STOKKARTI sk on sk.Kodu = sh.StokKodu
				LEFT JOIN AMUSTERI m on m.MUSNO = sh.CariNo
				left JOIN KASA k ON k.ISLEMNO = sh.IslemNo
				LEFT JOIN StokFiyatlari sf on sf.StokNo = sh.StokNo
				WHERE  FisTuru=''F'' AND (sh.IslemTuru = ''Prk.Satış'') AND k.BAACIKLA IN (''KK.Tahsilat'',''Tahsilat'')
				 AND  sh.FaturaTarihi >= ''@Tarih1'' and sh.FaturaTarihi <= ''@Tarih2'''+ @KulNoStr +'
				GROUP BY IslemNo,sh.IslemTuru,k.BAACIKLA,NakitVisa, m.MUSADI,m.MUSKOD,sh.StokKodu,sk.StokAdi,sh.StokAdi';
	END;

	SET @sql =  REPLACE(@Sql,'@Tarih1',@Tarih1)
	SET @sql =  REPLACE(@Sql,'@Tarih2',@Tarih2)		
--	PRINT @SQL
	EXEC sp_executesql  @sql;
END;
go-- 
  declare @CNTNAME NVARCHAR(1000),@SQL NVARCHAR(MAX)
select @CNTNAME= name  FROM sys.objects where type_desc like '%FUNCT%' and name like '%SplitString%'
   			
SET @SQL='DROP FUNCTION [dbo].['+CONVERT(VARCHAR(1000),@CNTNAME)+']'
EXEC(@SQL)
go--

CREATE  FUNCTION [dbo].[SplitString]
(    
      @Input NVARCHAR(MAX),
      @Character CHAR(1)
)
RETURNS @Output TABLE (
      Item NVARCHAR(1000)
)
AS
BEGIN
      DECLARE @StartIndex INT, @EndIndex INT

      SET @StartIndex = 1
      IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
      BEGIN
            SET @Input = @Input + @Character
      END

      WHILE CHARINDEX(@Character, @Input) > 0
      BEGIN
            SET @EndIndex = CHARINDEX(@Character, @Input)

            INSERT INTO @Output(Item)
            SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)

            SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
      END

      RETURN
END
go-- 
IF  EXISTS (SELECT *  FROM sys.views WHERE  name='Vstk_DepoDurumlari')
 BEGIN 
 drop view Vstk_DepoDurumlari
 end
go--
create  VIEW [dbo].[Vstk_DepoDurumlari]             
AS      --  SELECT * FROM Vstk_DepoDurumlari      
select *  from      
(select SK.StokNo, Kodu  ,Kodu StokKodu  , SK.StokAdi , GrupAdi , UreticiFirmaKodu , OzelKod1 , OzelKod2,  SK.AnaBirim , AktifPasif ,           
(select ISNULL(SUM(Miktar), 0)      from STOKHAR         where StokKodu = SK.Kodu and GC = 'G' and Depo = SH.Depo)     as [Giris],            
(select ISNULL(SUM(Miktar), 0)      from STOKHAR         where StokKodu = SK.Kodu and GC = 'C' and Depo = SH.Depo)     as [Cıkıs],            
((select ISNULL(SUM(Miktar), 0)      from STOKHAR         where StokKodu = SK.Kodu and GC = 'G' and Depo = SH.Depo)  -            
 (select ISNULL(SUM(Miktar), 0)      from STOKHAR         where StokKodu = SK.Kodu and GC = 'C' and Depo = SH.Depo)            
)            
    as [StokAdedi],            
 Depo, AsgariAdet,AzamiAdet,OlmasiGerekenAdet    
from   STOKKARTI as SK  LEFT JOIN STOKHAR SH ON SH.StokKodu=SK.Kodu          
WHERE SK.AktifPasif='A'      
group by SK.StokNo,Kodu ,   SK.StokAdi , GrupAdi , UreticiFirmaKodu , OzelKod1 , OzelKod2,  SK.AnaBirim , AktifPasif , SH.Depo,AsgariAdet,AzamiAdet,OlmasiGerekenAdet -- having  AktifPasif='A'       
)T  WHERE ((StokAdedi > 0.01) OR (EXISTS (Select 1 from Parametre Where Param = 'Envanter Raporlarında Sıfırın Altı Görünsün' AND Deger = '-1') AND StokAdedi < 0))
--order by StokAdedi 
go-- 


if not exists (SELECT 1 FROM VTGuncellemeleri WHERE VTVersiyon='7.2.5')
BEGIN
insert into VTGuncellemeleri (VTVersiyon, SonIslemNo, TarihSaat, Prg)
VALUES ('7.2.5',(select ISLEMNO from ADIGSABITLER ),GETDATE(),'OM')
END
go-- 

select top 5 * from VTGuncellemeleri order by VTVersiyon desc
   go--  
if exists (select * from sys.procedures where name='sp_Table_Trigger_EN_DS')
drop proc sp_Table_Trigger_EN_DS
go--
create  proc sp_Table_Trigger_EN_DS 
@tb  NVARCHAR(128) , @ed  NVARCHAR(128)
---Verilen tablo içindeki triggerları ENABLE-DISABLE yapalım.
--  sp_Table_Trigger_EN_DS 'STOKHAR','ENABLE'

as
DECLARE @triggerName NVARCHAR(128);
--DECLARE @tb NVARCHAR(128) = 'STOKHAR';
DECLARE @schemaName NVARCHAR(128) = 'dbo';
DECLARE @sql NVARCHAR(MAX);

DECLARE trigger_cursor CURSOR FOR
SELECT name
FROM sys.triggers
WHERE parent_id = OBJECT_ID(@schemaName + '.' + @tb);

OPEN trigger_cursor;
FETCH NEXT FROM trigger_cursor INTO @triggerName;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql = @ed +' TRIGGER [' + @triggerName + '] ON [' + @schemaName + '].[' + @tb + ']';
    EXEC sp_executesql @sql;

    FETCH NEXT FROM trigger_cursor INTO @triggerName;
END

CLOSE trigger_cursor;
DEALLOCATE trigger_cursor;

 go--


if  not  exists (select * from dbo.syscolumns where id = object_id(N'ASABIT') and name=N'KontrolTarihi')
begin
alter table ASABIT ADD   KontrolTarihi smalldatetime
end
else begin
alter table ASABIT alter column   KontrolTarihi smalldatetime
end
go--
if not exists (select * from sys.tables  where name='Sunucular')
begin 
CREATE TABLE Sunucular
(ID int IDENTITY(1,1),
 SunucuAdi nvarchar(50))
 end

go--
  declare @CNTNAME NVARCHAR(1000),@SQL NVARCHAR(MAX)
select @CNTNAME= name  FROM sys.objects where type_desc like '%FUNCT%' and name like '%ConvertTurkishToEnglishUpper%'
   			
SET @SQL='DROP FUNCTION [dbo].['+CONVERT(VARCHAR(1000),@CNTNAME)+']'
EXEC(@SQL)
go--
CREATE   FUNCTION dbo.ConvertTurkishToEnglishUpper
(
    @input NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    SET @input = UPPER(@input);
    SET @input = REPLACE(@input, 'İ', 'I');
    SET @input = REPLACE(@input, 'ı', 'I');
    SET @input = REPLACE(@input, 'Ş', 'S');
    SET @input = REPLACE(@input, 'ş', 'S');
    SET @input = REPLACE(@input, 'Ğ', 'G');
    SET @input = REPLACE(@input, 'ğ', 'G');
    SET @input = REPLACE(@input, 'Ü', 'U');
    SET @input = REPLACE(@input, 'ü', 'U');
    SET @input = REPLACE(@input, 'Ö', 'O');
    SET @input = REPLACE(@input, 'ö', 'O');
    SET @input = REPLACE(@input, 'Ç', 'C');
    SET @input = REPLACE(@input, 'ç', 'C');

    RETURN @input;
END;

go--
if exists (select * from sys.procedures where name='sp_SearchInStokKarti')
drop proc sp_SearchInStokKarti
go--
CREATE  PROCEDURE dbo.sp_SearchInStokKarti( 
	@searchText NVARCHAR(MAX),
	@otherText  NVARCHAR(MAX),
	@KayitSayisi INT,
	@OrderBy     NVARCHAR(50)
	)
AS
BEGIN
    -- Değişkenler
    DECLARE @sql NVARCHAR(MAX);
    DECLARE @searchWord NVARCHAR(255);
    DECLARE @delimiter CHAR(1) = ' ';
    DECLARE @index INT = 1;
    DECLARE @nextDelimiter INT;
    DECLARE @tempSearchText NVARCHAR(MAX);

    -- Arama metnini İngilizce karakterlere ve büyük harflere çevir
    SET @tempSearchText = dbo.ConvertTurkishToEnglishUpper(@searchText);

    -- Başlangıçta SQL sorgusunu oluştur
    SET @sql = 'SELECT TOP ('+CAST(@KayitSayisi as nvarchar(10))+') SK.*,StokAdedi,IkinciBirimMiktari,
						StokAdedi/IkinciBirimMiktari as IkinciBirimeGoreMiktar,
						StokAdedi/UcuncuBirimMiktari as UcuncuBirimeGoreMiktar,
						StokAdedi/DorduncuBirimMiktari as DorduncuBirimeGoreMiktar,
						StokAdedi/BesinciBirimMiktari as BesinciBirimeGoreMiktar,
						StokAdedi/AltinciBirimMiktari as AltinciBirimeGoreMiktar,
						IkinciBirimMiktari-IkinciBirimMiktari as KalanMiktar,
						IkinciBirimMiktari-IkinciBirimMiktari as StokAdedi_KalanMiktar, 
						IkinciBirimMiktari-IkinciBirimMiktari as VerilenKalanMiktar, 
						 CAST(0 as float) as RezerveMiktar, 
						(select TOP 1 MuafiyetAciklamasi from StokVergiMuafiyetleri vm where vm.StokKodu = SK.Kodu )MuafiyetAciklamasi   
				  FROM STOKKARTI SK WHERE 1=1';

    -- Arama metnini ayrıştırarak her kelime için kontrol ekle
    WHILE @index <= LEN(@tempSearchText) + 1
    BEGIN
        SET @nextDelimiter = CHARINDEX(@delimiter, @tempSearchText, @index);
        
        IF @nextDelimiter = 0
            SET @nextDelimiter = LEN(@tempSearchText) + 1;
        
        SET @searchWord = SUBSTRING(@tempSearchText, @index, @nextDelimiter - @index);
        
        IF LEN(@searchWord) > 0
        BEGIN
            -- MUSADI sütununu İngilizce karakterlere ve büyük harflere çevirerek karşılaştır
            SET @sql = @sql + ' AND dbo.ConvertTurkishToEnglishUpper(Kodu+StokAdi+StokAdi2) LIKE ''%' + @searchWord + '%''';
        END
        
        SET @index = @nextDelimiter + 1;
    END
	 SET @sql = @sql + @otherText + ' ORDER BY ' + @OrderBy  
        -- Dinamik SQL sorgusunu çalıştır
    EXEC sp_executesql @sql;
END;

go--
if exists (select * from sys.procedures where name='sp_SearchInAMUSTERI')
drop proc sp_SearchInAMUSTERI
go--
CREATE PROCEDURE dbo.sp_SearchInAMUSTERI( 
	@searchText NVARCHAR(MAX),
	@otherText  NVARCHAR(MAX),
	@KayitSayisi INT,
	@OrderBy     NVARCHAR(50)
	)
AS
BEGIN
    -- Değişkenler
    DECLARE @sql NVARCHAR(MAX);
    DECLARE @searchWord NVARCHAR(255);
    DECLARE @delimiter CHAR(1) = ' ';
    DECLARE @index INT = 1;
    DECLARE @nextDelimiter INT;
    DECLARE @tempSearchText NVARCHAR(MAX);

    -- Arama metnini İngilizce karakterlere ve büyük harflere çevir
    SET @tempSearchText = dbo.ConvertTurkishToEnglishUpper(@searchText);

    -- Başlangıçta SQL sorgusunu oluştur
    SET @sql = 'SELECT TOP ('+CAST(@KayitSayisi as nvarchar(10))+') AMUSTERI.*, 
                    (select sum(BorcToplami) as MUSBORC from VCr_CariKartlarBABTR where CariNo=MUSNO) as CariBorcToplami,
                    (select sum(AlacakToplami) as MUSALACAK from VCr_CariKartlarBABTR where CariNo=MUSNO) as CariAlacakToplami,
                    (select sum(Bakiye) as MUSBAKIYE from VCr_CariKartlarBABTR where CariNo=MUSNO) as CariBakiye,
                    GrupAdi as FiyatGrupAdi , 
                    (select TOP 1 Ulke from Adres where CariNo = MUSNO and AdresNo=1) as Ulke 
                    from AMUSTERI LEFT OUTER JOIN GRUP ON FiyatGrupNo = NoId 
                    where MUSDURUM =''A''';

    -- Arama metnini ayrıştırarak her kelime için kontrol ekle
    WHILE @index <= LEN(@tempSearchText) + 1
    BEGIN
        SET @nextDelimiter = CHARINDEX(@delimiter, @tempSearchText, @index);
        
        IF @nextDelimiter = 0
            SET @nextDelimiter = LEN(@tempSearchText) + 1;
        
        SET @searchWord = SUBSTRING(@tempSearchText, @index, @nextDelimiter - @index);
        
        IF LEN(@searchWord) > 0
        BEGIN
            -- MUSADI sütununu İngilizce karakterlere ve büyük harflere çevirerek karşılaştır
            SET @sql = @sql + ' AND dbo.ConvertTurkishToEnglishUpper(MUSKOD+MUSADI+MUSIL+MUSILCE) LIKE ''%' + @searchWord + '%''';
        END
        
        SET @index = @nextDelimiter + 1;
    END
	 SET @sql = @sql + @otherText + ' ORDER BY ' + @OrderBy  
        -- Dinamik SQL sorgusunu çalıştır
    EXEC sp_executesql @sql;
END;
go--


 IF NOT EXISTS (SELECT *  FROM sys.tables WHERE  name='Sunucular')
 BEGIN 
CREATE TABLE Sunucular
(ID int IDENTITY(1,1),
 SunucuAdi nvarchar(50))
 end;
 go--

UPDATE k 
   SET k.DovizNoId = d.NoId,k.DovizAdi = d.DovizAdi 
  FROM KASAT k,DOVIZT d
 WHERE k.DovizKodu = d.DovizKodu

UPDATE k 
   SET k.DovizCinsi = d.NoId
  FROM KASA k,DOVIZT d
 WHERE k.DovizKodu = d.DovizKodu
   AND k.DovizCinsi <> d.NoId

UPDATE h 
   SET h.DovizCinsi = d.NoId,
	   h.DovizNoId = d.NoId,
	   h.DovizAdi  = d.DovizAdi
  FROM HESAPLAR h,DOVIZT d
 WHERE h.DovizKodu = d.DovizKodu   

 UPDATE b 
   SET b.DovizCinsi = d.NoId
  FROM BANKA b,DOVIZT d
 WHERE b.DovizKodu = d.DovizKodu
   AND b.DovizCinsi <> d.NoId

DEclare @No int
DECLARE users CURSOR
FOR            
SELECT No FROM Kullanicilar 
OPEN users
FETCH NEXT FROM users INTO @No
WHILE @@FETCH_STATUS = 0
  BEGIN		
		UPDATE KullaniciAyarlari 
		   SET Deger = (Select DISTINCT d.DovizAdi from DOVIZT d,KullaniciAyarlari k where k.Deger = d.DovizKodu and k.Ayar = 'VarsayilanDovizKodu' and KullaniciNo = @No)
		 WHERE Ayar = 'VarsayilanDovizAdi' and KullaniciNo = @No 

		 UPDATE KullaniciAyarlari 
		   SET Deger = (Select DISTINCT d.NoId from DOVIZT d,KullaniciAyarlari k where k.Deger = d.DovizKodu and k.Ayar = 'VarsayilanDovizKodu' and KullaniciNo = @No )
		 WHERE Ayar = 'VarsayilanDovizId' and KullaniciNo = @No

		UPDATE KullaniciAyarlari 
		   SET Deger = (Select DISTINCT d.NoId from DOVIZT d,KullaniciAyarlari k,KASAT t where k.Deger = t.KASAKODU and t.DovizKodu = d.DovizKodu and k.Ayar = 'Varsayılan Visa Kasa Kodu' and KullaniciNo = @No)
		 WHERE Ayar = 'Varsayılan Visa Kasa Döviz Kodu' and KullaniciNo = @No
    FETCH NEXT FROM users INTO @No
  END
CLOSE users
DEALLOCATE users



GO--
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.ConvertTurkishToEnglishUpper') AND type = N'FN')
BEGIN
    DROP FUNCTION dbo.ConvertTurkishToEnglishUpper;
END;
GO--
CREATE  FUNCTION dbo.ConvertTurkishToEnglishUpper
(
    @input NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    SET @input = UPPER(@input);
    SET @input = REPLACE(@input, 'İ', 'I');
    SET @input = REPLACE(@input, 'ı', 'I');
    SET @input = REPLACE(@input, 'Ş', 'S');
    SET @input = REPLACE(@input, 'ş', 'S');
    SET @input = REPLACE(@input, 'Ğ', 'G');
    SET @input = REPLACE(@input, 'ğ', 'G');
    SET @input = REPLACE(@input, 'Ü', 'U');
    SET @input = REPLACE(@input, 'ü', 'U');
    SET @input = REPLACE(@input, 'Ö', 'O');
    SET @input = REPLACE(@input, 'ö', 'O');
    SET @input = REPLACE(@input, 'Ç', 'C');
    SET @input = REPLACE(@input, 'ç', 'C');

    RETURN @input;
END;

GO--		
if exists (select * from sys.procedures where name='sp_SearchInStokKarti')
drop proc sp_SearchInStokKarti
GO--


CREATE  PROCEDURE dbo.sp_SearchInStokKarti( 
	@searchText NVARCHAR(MAX),
	@otherText  NVARCHAR(MAX),
	@KayitSayisi INT,
	@OrderBy     NVARCHAR(50)
	)
AS
BEGIN
    -- Değişkenler
    DECLARE @sql NVARCHAR(MAX);
    DECLARE @searchWord NVARCHAR(255);
    DECLARE @delimiter CHAR(1) = ' ';
    DECLARE @index INT = 1;
    DECLARE @nextDelimiter INT;
    DECLARE @tempSearchText NVARCHAR(MAX);

    -- Arama metnini İngilizce karakterlere ve büyük harflere çevir
    SET @tempSearchText = dbo.ConvertTurkishToEnglishUpper(@searchText);

    -- Başlangıçta SQL sorgusunu oluştur
    SET @sql = 'SELECT TOP ('+CAST(@KayitSayisi as nvarchar(10))+') SK.*,StokAdedi,IkinciBirimMiktari,
						StokAdedi/IkinciBirimMiktari as IkinciBirimeGoreMiktar,
						StokAdedi/UcuncuBirimMiktari as UcuncuBirimeGoreMiktar,
						StokAdedi/DorduncuBirimMiktari as DorduncuBirimeGoreMiktar,
						StokAdedi/BesinciBirimMiktari as BesinciBirimeGoreMiktar,
						StokAdedi/AltinciBirimMiktari as AltinciBirimeGoreMiktar,
						IkinciBirimMiktari-IkinciBirimMiktari as KalanMiktar,
						IkinciBirimMiktari-IkinciBirimMiktari as StokAdedi_KalanMiktar, 
						IkinciBirimMiktari-IkinciBirimMiktari as VerilenKalanMiktar, 
						 CAST(0 as float) as RezerveMiktar, 
						(select TOP 1 MuafiyetAciklamasi from StokVergiMuafiyetleri vm where vm.StokKodu = SK.Kodu )MuafiyetAciklamasi   
				  FROM STOKKARTI SK WHERE 1=1';

    -- Arama metnini ayrıştırarak her kelime için kontrol ekle
    WHILE @index <= LEN(@tempSearchText) + 1
    BEGIN
        SET @nextDelimiter = CHARINDEX(@delimiter, @tempSearchText, @index);
        
        IF @nextDelimiter = 0
            SET @nextDelimiter = LEN(@tempSearchText) + 1;
        
        SET @searchWord = SUBSTRING(@tempSearchText, @index, @nextDelimiter - @index);
        
        IF LEN(@searchWord) > 0
        BEGIN
            -- MUSADI sütununu İngilizce karakterlere ve büyük harflere çevirerek karşılaştır
            SET @sql = @sql + ' AND dbo.ConvertTurkishToEnglishUpper(Kodu+StokAdi+StokAdi2) LIKE ''%' + @searchWord + '%''';
        END
        
        SET @index = @nextDelimiter + 1;
    END
	 SET @sql = @sql + @otherText + ' ORDER BY ' + @OrderBy  
        -- Dinamik SQL sorgusunu çalıştır
    EXEC sp_executesql @sql;
END;

go--
if exists (select * from sys.procedures where name='sp_SearchInAMUSTERI')
drop proc sp_SearchInAMUSTERI
GO--
CREATE  PROCEDURE dbo.sp_SearchInAMUSTERI( 
	@searchText NVARCHAR(MAX),
	@otherText  NVARCHAR(MAX),
	@KayitSayisi INT,
	@OrderBy     NVARCHAR(50)
	)
AS
BEGIN
    -- Değişkenler
    DECLARE @sql NVARCHAR(MAX);
    DECLARE @searchWord NVARCHAR(255);
    DECLARE @delimiter CHAR(1) = ' ';
    DECLARE @index INT = 1;
    DECLARE @nextDelimiter INT;
    DECLARE @tempSearchText NVARCHAR(MAX);

    -- Arama metnini İngilizce karakterlere ve büyük harflere çevir
    SET @tempSearchText = dbo.ConvertTurkishToEnglishUpper(@searchText);

    -- Başlangıçta SQL sorgusunu oluştur
    SET @sql = 'SELECT TOP ('+CAST(@KayitSayisi as nvarchar(10))+') AMUSTERI.*, 
                    (select sum(BorcToplami) as MUSBORC from VCr_CariKartlarBABTR where CariNo=MUSNO) as CariBorcToplami,
                    (select sum(AlacakToplami) as MUSALACAK from VCr_CariKartlarBABTR where CariNo=MUSNO) as CariAlacakToplami,
                    (select sum(Bakiye) as MUSBAKIYE from VCr_CariKartlarBABTR where CariNo=MUSNO) as CariBakiye,
                    GrupAdi as FiyatGrupAdi , 
                    (select TOP 1 Ulke from Adres where CariNo = MUSNO and AdresNo=1) as Ulke 
                    from AMUSTERI LEFT OUTER JOIN GRUP ON FiyatGrupNo = NoId 
                    where MUSDURUM =''A''';

    -- Arama metnini ayrıştırarak her kelime için kontrol ekle
    WHILE @index <= LEN(@tempSearchText) + 1
    BEGIN
        SET @nextDelimiter = CHARINDEX(@delimiter, @tempSearchText, @index);
        
        IF @nextDelimiter = 0
            SET @nextDelimiter = LEN(@tempSearchText) + 1;
        
        SET @searchWord = SUBSTRING(@tempSearchText, @index, @nextDelimiter - @index);
        
        IF LEN(@searchWord) > 0
        BEGIN
            -- MUSADI sütununu İngilizce karakterlere ve büyük harflere çevirerek karşılaştır
            SET @sql = @sql + ' AND dbo.ConvertTurkishToEnglishUpper(MUSKOD+MUSADI+MUSIL+MUSILCE) LIKE ''%' + @searchWord + '%''';
        END
        
        SET @index = @nextDelimiter + 1;
    END
	 SET @sql = @sql + @otherText + ' ORDER BY ' + @OrderBy  
        -- Dinamik SQL sorgusunu çalıştır
    EXEC sp_executesql @sql;
END;


go--
if exists (select * from sys.procedures where name='sp_Table_Trigger_EN_DS')
drop proc sp_Table_Trigger_EN_DS
go--
create  proc sp_Table_Trigger_EN_DS 
@tb  NVARCHAR(128) , @ed  NVARCHAR(128)
---Verilen tablo içindeki triggerları ENABLE-DISABLE yapalım.
--  sp_Table_Trigger_EN_DS 'STOKHAR','ENABLE'

as
DECLARE @triggerName NVARCHAR(128);
--DECLARE @tb NVARCHAR(128) = 'STOKHAR';
DECLARE @schemaName NVARCHAR(128) = 'dbo';
DECLARE @sql NVARCHAR(MAX);

DECLARE trigger_cursor CURSOR FOR
SELECT name
FROM sys.triggers
WHERE parent_id = OBJECT_ID(@schemaName + '.' + @tb);

OPEN trigger_cursor;
FETCH NEXT FROM trigger_cursor INTO @triggerName;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql = @ed +' TRIGGER [' + @triggerName + '] ON [' + @schemaName + '].[' + @tb + ']';
    EXEC sp_executesql @sql;

    FETCH NEXT FROM trigger_cursor INTO @triggerName;
END

CLOSE trigger_cursor;
DEALLOCATE trigger_cursor;

GO
--   sp_Table_Trigger_EN_DS 'STOKHAR','DISABLE'

--  select * from sys.triggers
 
 
 go--


if  not  exists (select * from dbo.syscolumns where id = object_id(N'StokBarkodlari') and name=N'RenkBeden')
begin
ALTER TABLE StokBarkodlari ADD RenkBeden bit
end
else begin
ALTER TABLE StokBarkodlari alter column RenkBeden bit
end
go--
if  not  exists (select * from dbo.syscolumns where id = object_id(N'StokBarkodlari') and name=N'RenkBedenId')
begin
ALTER TABLE StokBarkodlari ADD RenkBedenId INT
end
else begin
ALTER TABLE StokBarkodlari alter column RenkBedenId int
end

UPDATE KullaniciAyarlari SET Deger='999' WHERE Ayar='Adisyon Server Kontrol Süre'
GO--

UPDATE STOKHAR SET Miktar = Miktar * -1 , GC= 'G' where Miktar < 0 and GC  = 'C'
UPDATE STOKHAR SET Miktar = Miktar * -1 , GC= 'C' where Miktar < 0 and GC  = 'G'
go--
UPDATE k 
   SET k.DovizNoId = d.NoId,k.DovizAdi = d.DovizAdi 
  FROM KASAT k,DOVIZT d
 WHERE k.DovizKodu = d.DovizKodu

UPDATE k 
   SET k.DovizCinsi = d.NoId
  FROM KASA k,DOVIZT d
 WHERE k.DovizKodu = d.DovizKodu
   AND k.DovizCinsi <> d.NoId

UPDATE h 
   SET h.DovizCinsi = d.NoId,
	   h.DovizNoId = d.NoId,
	   h.DovizAdi  = d.DovizAdi
  FROM HESAPLAR h,DOVIZT d
 WHERE h.DovizKodu = d.DovizKodu   

 UPDATE b 
   SET b.DovizCinsi = d.NoId
  FROM BANKA b,DOVIZT d
 WHERE b.DovizKodu = d.DovizKodu
   AND b.DovizCinsi <> d.NoId

DEclare @No int
DECLARE users CURSOR
FOR            
SELECT No FROM Kullanicilar 
OPEN users
FETCH NEXT FROM users INTO @No
WHILE @@FETCH_STATUS = 0
  BEGIN		
		UPDATE KullaniciAyarlari 
		   SET Deger = (Select DISTINCT d.DovizAdi from DOVIZT d,KullaniciAyarlari k where k.Deger = d.DovizKodu and k.Ayar = 'VarsayilanDovizKodu' and KullaniciNo = @No)
		 WHERE Ayar = 'VarsayilanDovizAdi' and KullaniciNo = @No 

		 UPDATE KullaniciAyarlari 
		   SET Deger = (Select DISTINCT d.NoId from DOVIZT d,KullaniciAyarlari k where k.Deger = d.DovizKodu and k.Ayar = 'VarsayilanDovizKodu' and KullaniciNo = @No )
		 WHERE Ayar = 'VarsayilanDovizId' and KullaniciNo = @No

		UPDATE KullaniciAyarlari 
		   SET Deger = (Select DISTINCT d.NoId from DOVIZT d,KullaniciAyarlari k,KASAT t where k.Deger = t.KASAKODU and t.DovizKodu = d.DovizKodu and k.Ayar = 'Varsayılan Visa Kasa Kodu' and KullaniciNo = @No)
		 WHERE Ayar = 'Varsayılan Visa Kasa Döviz Kodu' and KullaniciNo = @No
    FETCH NEXT FROM users INTO @No
  END
CLOSE users
DEALLOCATE users



go--
  declare @CNTNAME NVARCHAR(1000),@SQL NVARCHAR(MAX)
select @CNTNAME= name  FROM sys.objects where type_desc like '%FUNCT%' and name like '%ConvertTurkishToEnglishUpper%'
   			
SET @SQL='DROP FUNCTION [dbo].['+CONVERT(VARCHAR(1000),@CNTNAME)+']'
EXEC(@SQL)
go--
CREATE FUNCTION dbo.ConvertTurkishToEnglishUpper
(
    @input NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    SET @input = UPPER(@input);
    SET @input = REPLACE(@input, 'İ', 'I');
    SET @input = REPLACE(@input, 'ı', 'I');
    SET @input = REPLACE(@input, 'Ş', 'S');
    SET @input = REPLACE(@input, 'ş', 'S');
    SET @input = REPLACE(@input, 'Ğ', 'G');
    SET @input = REPLACE(@input, 'ğ', 'G');
    SET @input = REPLACE(@input, 'Ü', 'U');
    SET @input = REPLACE(@input, 'ü', 'U');
    SET @input = REPLACE(@input, 'Ö', 'O');
    SET @input = REPLACE(@input, 'ö', 'O');
    SET @input = REPLACE(@input, 'Ç', 'C');
    SET @input = REPLACE(@input, 'ç', 'C');

    RETURN @input;
END;

go--

if exists (select * from sys.procedures where name='sp_SearchInStokKarti')
drop proc sp_SearchInStokKarti
go--
CREATE  PROCEDURE dbo.sp_SearchInStokKarti( 
	@searchText NVARCHAR(MAX),
	@otherText  NVARCHAR(MAX),
	@KayitSayisi INT,
	@OrderBy     NVARCHAR(50)
	)
AS
BEGIN
    -- Değişkenler
    DECLARE @sql NVARCHAR(MAX);
    DECLARE @searchWord NVARCHAR(255);
    DECLARE @delimiter CHAR(1) = ' ';
    DECLARE @index INT = 1;
    DECLARE @nextDelimiter INT;
    DECLARE @tempSearchText NVARCHAR(MAX);

    -- Arama metnini İngilizce karakterlere ve büyük harflere çevir
    SET @tempSearchText = dbo.ConvertTurkishToEnglishUpper(@searchText);

    -- Başlangıçta SQL sorgusunu oluştur
    SET @sql = 'SELECT TOP ('+CAST(@KayitSayisi as nvarchar(10))+') SK.*,StokAdedi,IkinciBirimMiktari,
						StokAdedi/IkinciBirimMiktari as IkinciBirimeGoreMiktar,
						StokAdedi/UcuncuBirimMiktari as UcuncuBirimeGoreMiktar,
						StokAdedi/DorduncuBirimMiktari as DorduncuBirimeGoreMiktar,
						StokAdedi/BesinciBirimMiktari as BesinciBirimeGoreMiktar,
						StokAdedi/AltinciBirimMiktari as AltinciBirimeGoreMiktar,
						IkinciBirimMiktari-IkinciBirimMiktari as KalanMiktar,
						IkinciBirimMiktari-IkinciBirimMiktari as StokAdedi_KalanMiktar, 
						IkinciBirimMiktari-IkinciBirimMiktari as VerilenKalanMiktar, 
						 CAST(0 as float) as RezerveMiktar, 
						(select TOP 1 MuafiyetAciklamasi from StokVergiMuafiyetleri vm where vm.StokKodu = SK.Kodu )MuafiyetAciklamasi   
				  FROM STOKKARTI SK WHERE 1=1';

    -- Arama metnini ayrıştırarak her kelime için kontrol ekle
    WHILE @index <= LEN(@tempSearchText) + 1
    BEGIN
        SET @nextDelimiter = CHARINDEX(@delimiter, @tempSearchText, @index);
        
        IF @nextDelimiter = 0
            SET @nextDelimiter = LEN(@tempSearchText) + 1;
        
        SET @searchWord = SUBSTRING(@tempSearchText, @index, @nextDelimiter - @index);
        
        IF LEN(@searchWord) > 0
        BEGIN
            -- MUSADI sütununu İngilizce karakterlere ve büyük harflere çevirerek karşılaştır
            SET @sql = @sql + ' AND dbo.ConvertTurkishToEnglishUpper(Kodu+StokAdi+StokAdi2) LIKE ''%' + @searchWord + '%''';
        END
        
        SET @index = @nextDelimiter + 1;
    END
	 SET @sql = @sql + @otherText + ' ORDER BY ' + @OrderBy  
        -- Dinamik SQL sorgusunu çalıştır
    EXEC sp_executesql @sql;
END;

go--
if exists (select * from sys.procedures where name='sp_SearchInAMUSTERI')
drop proc sp_SearchInAMUSTERI
go--
CREATE  PROCEDURE dbo.sp_SearchInAMUSTERI( 
	@searchText NVARCHAR(MAX),
	@otherText  NVARCHAR(MAX),
	@KayitSayisi INT,
	@OrderBy     NVARCHAR(50)
	)
AS
BEGIN
    -- Değişkenler
    DECLARE @sql NVARCHAR(MAX);
    DECLARE @searchWord NVARCHAR(255);
    DECLARE @delimiter CHAR(1) = ' ';
    DECLARE @index INT = 1;
    DECLARE @nextDelimiter INT;
    DECLARE @tempSearchText NVARCHAR(MAX);

    -- Arama metnini İngilizce karakterlere ve büyük harflere çevir
    SET @tempSearchText = dbo.ConvertTurkishToEnglishUpper(@searchText);

    -- Başlangıçta SQL sorgusunu oluştur
    SET @sql = 'SELECT TOP ('+CAST(@KayitSayisi as nvarchar(10))+') AMUSTERI.*, 
                    (select sum(BorcToplami) as MUSBORC from VCr_CariKartlarBABTR where CariNo=MUSNO) as CariBorcToplami,
                    (select sum(AlacakToplami) as MUSALACAK from VCr_CariKartlarBABTR where CariNo=MUSNO) as CariAlacakToplami,
                    (select sum(Bakiye) as MUSBAKIYE from VCr_CariKartlarBABTR where CariNo=MUSNO) as CariBakiye,
                    GrupAdi as FiyatGrupAdi , 
                    (select TOP 1 Ulke from Adres where CariNo = MUSNO and AdresNo=1) as Ulke 
                    from AMUSTERI LEFT OUTER JOIN GRUP ON FiyatGrupNo = NoId 
                    where MUSDURUM =''A''';

    -- Arama metnini ayrıştırarak her kelime için kontrol ekle
    WHILE @index <= LEN(@tempSearchText) + 1
    BEGIN
        SET @nextDelimiter = CHARINDEX(@delimiter, @tempSearchText, @index);
        
        IF @nextDelimiter = 0
            SET @nextDelimiter = LEN(@tempSearchText) + 1;
        
        SET @searchWord = SUBSTRING(@tempSearchText, @index, @nextDelimiter - @index);
        
        IF LEN(@searchWord) > 0
        BEGIN
            -- MUSADI sütununu İngilizce karakterlere ve büyük harflere çevirerek karşılaştır
            SET @sql = @sql + ' AND dbo.ConvertTurkishToEnglishUpper(MUSKOD+MUSADI+MUSIL+MUSILCE) LIKE ''%' + @searchWord + '%''';
        END
        
        SET @index = @nextDelimiter + 1;
    END
	 SET @sql = @sql + @otherText + ' ORDER BY ' + @OrderBy  
        -- Dinamik SQL sorgusunu çalıştır
    EXEC sp_executesql @sql;
END;


go--
if exists (select * from sys.procedures where name='sp_Table_Trigger_EN_DS')
drop proc sp_Table_Trigger_EN_DS
go--

create  proc sp_Table_Trigger_EN_DS 
@tb  NVARCHAR(128) , @ed  NVARCHAR(128)
---Verilen tablo içindeki triggerları ENABLE-DISABLE yapalım.
--  sp_Table_Trigger_EN_DS 'STOKHAR','ENABLE'

as
DECLARE @triggerName NVARCHAR(128);
--DECLARE @tb NVARCHAR(128) = 'STOKHAR';
DECLARE @schemaName NVARCHAR(128) = 'dbo';
DECLARE @sql NVARCHAR(MAX);

DECLARE trigger_cursor CURSOR FOR
SELECT name
FROM sys.triggers
WHERE parent_id = OBJECT_ID(@schemaName + '.' + @tb);

OPEN trigger_cursor;
FETCH NEXT FROM trigger_cursor INTO @triggerName;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql = @ed +' TRIGGER [' + @triggerName + '] ON [' + @schemaName + '].[' + @tb + ']';
    EXEC sp_executesql @sql;

    FETCH NEXT FROM trigger_cursor INTO @triggerName;
END

CLOSE trigger_cursor;
DEALLOCATE trigger_cursor;
 
 go--

if exists (select * from sys.procedures where name='sp_FifoMaliyetlendirme')
drop proc sp_FifoMaliyetlendirme
go--

 
 create proc sp_FifoMaliyetlendirme  @Tarih varchar(8), @stokkodu varchar(50)              
as              
-- sp_FifoMaliyetlendirme '20221212','635'    
create table  #StokHar   (sira int, noid int, stokkodu nvarchar(50), GC nvarchar(1),         
Miktar float,KalanMiktar float, BirimFiyat money, FaturaTarihi varchar(8),fifo money ,           
CONSTRAINT [PK_#StokHar] PRIMARY KEY CLUSTERED         
(        
 sira ASC        
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]        
) ON [PRIMARY]        
   --Geçici tablo ile seçilen karta ait son tarih öncesi Stok hareketleri aktarıldı.Tarih ve noya göre sıralandı.              
insert into #StokHar          
select ROW_NUMBER() OVER(ORDER BY FaturaTarihi ASC,NoId) AS Row,NoId,StokKodu,GC, Miktar,              
case when GC='G' then Miktar else 0 end as Kalan,((SonTutar+SatMasrafTutari)/Miktar), FaturaTarihi,0 as fifo from STOKHAR               
WHERE StokKodu = @Stokkodu    and FaturaTarihi<= @Tarih and FisTuru <> 'İ'  and Miktar>0.0000001    AND IslemTuru<>'DepoVirman' 
order by Row               
      
DECLARE @KulNo int      
SET @KulNo = 1  
DECLARE @logId int  
SET @logId = (Select MIN(noid) from #StokHar)      
      
INSERT INTO FifoLifoLog (NoId,StokKodu, Durum ,KayitSayisi,BaslamaTarihi,KulNo)      
SElect @logId,@stokkodu,0,count(*),GETDATE(),@KulNo from #StokHar      
      
Declare @Stok float              
Declare @NoId int              
Declare @id int              
Declare @maxid int              
Declare @GC varchar(1)              
Declare @Miktar float              
Declare @Fiyat money              
Declare @tnoid int              
Declare @fifo money              
              
set @Stok=0              
set @id=1              
              
select @Maxid=count(*) from #StokHar   where StokKodu =@StokKodu        
           
while @id <= @maxid              
begin         
--  print('Sıra No '+convert(varchar,@id)+'/'+convert(varchar,@Maxid))        
  select @NoId=noid,@GC=GC, @Miktar=Miktar,   @Fiyat=(BirimFiyat)  from #StokHar  where sira=@id              
              
  if @GC='G'               
    set @Stok = @Stok+@Miktar    --@Stok tanımla ve G Miktarı ekle          
   else              
    begin               
    set @fifo=0              
    Declare @tmik float              
    Declare @tfifo money              
    Declare @dmiktar float              
    Declare @parcali int              
              
    set @parcali=0     --Önceki Girişten kalan varmı?          
    set @dmiktar=@Miktar          --Yoksa Miktar direk yazıyor.    
    --print('Miktar'+convert(varchar,@Miktar))        
          
    while @Miktar > 0              
  begin               
    select top(1) @tnoid=noid, @tmik=KalanMiktar, @tfifo=birimfiyat from #StokHar               
    where KalanMiktar>0              
              
   if @tnoid=0               
     begin               
      set @miktar=0              
       select top(1) @tfifo=birimfiyat from #StokHar where GC='G' order by FaturaTarihi desc              
     end              
     else              
      begin                    
     update #StokHar set KalanMiktar = case when KalanMiktar-@miktar >0 then KalanMiktar-@miktar else  0 end               
     where noid=@tnoid              
              
     set @miktar=@Miktar-@tmik;              
               end                 
                  
      if (@miktar>0) or (@parcali=1)               
     begin              
        set @parcali=1              
  if @Miktar>0              
   set @fifo=@fifo + ((@tfifo * (@tmik))/@dmiktar)               
  else              
   set @fifo=@fifo + ((@tfifo * (@tmik+@Miktar))/@dmiktar)               
     end              
                  
            if @parcali=0               
     set @fifo=@tfifo                      
      
    end              
 -- update STOKHAR set FifoFiyat = @fifo where NoId=@NoId            
  update #StokHar set fifo = @fifo where noid=@NoId            
         
    end         
  set @id=@id+1             
end         
--   select count(*) from   #StokHar where fifo<>0 ---and @id in (100,500,5000,10000,20000,30000,40000,50000,70000)    
  ALTER TABLE STOKHAR DISABLE TRIGGER STOKHAR_Degisim  
  update STOKHAR set FifoFiyat =fifo from STOKHAR inner join #StokHar as tmpStokHar on tmpStokHar.noid=STOKHAR.NoId    
  ALTER TABLE STOKHAR ENABLE TRIGGER STOKHAR_Degisim    
      
UPDATE FifoLifoLog SET BitisTarihi = GETDATE() , Durum=1   WHERE NoId = @logId      

go--
if exists (select * from sys.procedures where name='sp_FaturaIslemleriListesi')
drop proc sp_FaturaIslemleriListesi
go--



CREATE PROCEDURE [dbo].[sp_FaturaIslemleriListesi]                                                    
  @tarih1 varchar(20),                                                     
  @tarih2 varchar(20),                                                    
  @dep varchar(500),                                                    
  @orderby int,                                                    
  @arama varchar(100),                                                    
  @GosterilecekKayit int,                                                    
  @IslemTuru varchar(20),                                                    
  @Durumu int,                                        
  @IslemTipi  varchar(30),                            
  @FatSerNo  varchar(3),                            
  @eFaturaNo  varchar(30),                            
  @FaturaTuru varchar(1),                
  @IslemNoLike bit = 0,                  
  @TP varchar(2) = 'TF'      
AS                                                    
                        
declare @str nvarchar(max)                                                    
declare @rc int                                                     
declare @tmp table (trc int)                                                    
declare @ayrac varchar(2)                            
declare @peFaturaNo varchar(50)                    
if @eFaturaNo<>''                    
select @peFaturaNo=UPPER(@eFaturaNo)                    
else set @peFaturaNo=''                    
set @ayrac='"';         
        
declare @tstr varchar(100);        
        
if @orderby in (0,9)                                                    
  set @tstr='IslemNo DESC'                                                    
if @orderby=1                                                     
 set @tstr='FaturaNo DESC,IslemNo DESC'                                                     
if @orderby=2                                                     
 set @tstr='CariAdi DESC,IslemNo DESC'                                                    
if @orderby=3                                                     
 set @tstr='CariKodu DESC,IslemNo DESC'                                                     
if @orderby=4                                                    
 set @tstr='KULADI DESC,IslemNo DESC'                                                    
if @orderby=5                                                    
 set @tstr='SaticiAdi DESC,IslemNo DESC'                                          
if @orderby=6                                                    
 set @tstr='eFaturaDurumu DESC,IslemNo DESC'                             
 if @orderby=7                                                    
 set @tstr='YaziciCount DESC,IslemNo DESC'                             
 if @orderby=8                                                    
 set @tstr='FaturaTarihi DESC,IslemNo DESC'   
   
set @str='select * from (select TOP ' + CAST(@GosterilecekKayit as nvarchar(10)) + ' ROW_NUMBER() over (order by '+@tstr+') as sira,'''' as plaka,*'+           
            ' from STOKHARDETBAG where FisTuru = '''+ @FaturaTuru + ''' AND TP = '''+ @TP + ''' AND FaturaTarihi >='''+ @Tarih1+ ''' and FaturaTarihi <= '''+@Tarih2+'''';                 
            
if @peFaturaNo<>''                            
set @str=@str+'and upper(eFaturaNo) like upper(''%'+@peFaturaNo+'%'') '               
            
if @FatSerNo<>''                            
set @str=@str+'and Replace(FatSerNo,'''''''','''+@ayrac+''') = '''+@FatSerNo+''' '              
                                               
if @dep <> ''                                                    
 set @str=@str+' and Departman in ('+@Dep+')'                                                    
if @IslemTuru <> 'Tümü'                                                    
 set @str=@str+' and IslemTuru = '''+@IslemTuru+''''                                      
if @IslemTipi <> 'Tümü' and   @IslemTipi <> ''                                                   
 set @str=@str+' and IslemTipi like ''%'+@IslemTipi+'%'''                                          
                
if @arama <> ''                 
begin                
if @orderby=0                 
begin                
 if @IslemNoLike = 0                
 set @str=@str+'and CAST(IslemNo as nvarchar(20)) = '''+@arama+''' '                 
 else                
 set @str=@str+'and IslemNo like ''%'+@arama+'%'' '                 
end;                                                  
if @orderby=1                                                     
 set @str=@str+'and upper(FaturaNo) like upper('''+@arama+'%'') '                                                     
if @orderby=2                                                     
 set @str=@str+'and upper(CariAdi) like upper(''%'+@arama+'%'') '                                                    
if @orderby=3                                                     
 set @str=@str+'and upper(CariKodu) like upper('''+@arama+'%'') '                                                     
if @orderby=4                                                    
 set @str=@str+'and upper(KULADI) like upper(''%'+@arama+'%'') '                                                    
if @orderby=5                                                    
 set @str=@str+'and upper(SaticiAdi) like upper(''%'+@arama+'%'') '                                         
 if @orderby=6                                                    
 set @str=@str+'and upper(eFaturaDurumu) like upper(''%'+@arama+'%'') '                                         
if @orderby=7                                                    
 set @str=@str+'and upper(YaziciCount) like upper(''%'+@arama+'%'') '                                         
if @orderby=8                                                    
 set @str=@str+'and upper(FaturaTarihi) like upper(''%'+@arama+'%'') '                       
if @orderby=9                                                    
 set @str=@str+'and ((upper(Ack1) like upper(''%'+@arama+'%'')) or (upper(Ack2) like upper(''%'+@arama+'%'')) or (upper(Ack3) like upper(''%'+@arama+'%'')) or (upper(Ack4) like upper(''%'+@arama+'%''))               
   or EXISTS (Select 1 from ACARI AC where AC.ISLEMNO = IslemNo and upper(Aciklama2) like upper(''%'+@arama+'%''))              
      or EXISTS (Select 1 from ACIKLAMA AC where AC.FATURANO = IslemNo and upper(TeslimEden) like upper(''%'+@arama+'%''))              
      or EXISTS (Select 1 from ACIKLAMA AC where AC.FATURANO = IslemNo and upper(TeslimAlan) like upper(''%'+@arama+'%''))) '                 
end;   
  
  
-- set @str=@str+')tbl ORDER BY IslemNo';                                                                      
   
  
if @orderby=0                                                     
 set @str=@str+')tbl ORDER BY IslemNo';                                                 
if @orderby=1                                                     
 set @str=@str+')tbl ORDER BY FaturaNo,IslemNo';                                                 
if @orderby=2                                                     
 set @str=@str+')tbl ORDER BY CariAdi ,IslemNo';     
if @orderby=3                                                     
 set @str=@str+')tbl ORDER BY CariKodu ,IslemNo';   
if @orderby=4                                                    
 set @str=@str+')tbl ORDER BY KULADI ,IslemNo';   
if @orderby=5                                                    
 set @str=@str+')tbl ORDER BY SaticiAdi,IslemNo';   
if @orderby=6      
 set @str=@str+')tbl ORDER BY eFaturaDurumu,IslemNo';   
if @orderby=7                                                    
 set @str=@str+')tbl ORDER BY YaziciCount,IslemNo';   
if @orderby=8                                                    
 set @str=@str+')tbl ORDER BY FaturaTarihi,IslemNo';   
if @orderby= 9                                                   
 set @str=@str+')tbl ORDER BY IslemNo';   
          
execute sp_executesql  @str   

GO--

if exists (select * from sys.procedures where name='sp_CARIEKSTRE')
drop proc sp_CARIEKSTRE
go--
CREATE   PROCEDURE [dbo].[sp_CARIEKSTRE]                   
@MUSNO nvarchar(30), @ILKTARIH nvarchar(10),@SONTARIH nvarchar(10),                       
 @KAPALIHAREKET nvarchar(1),@ORTVADESEC nvarchar(1),@ISLEMTIPINEGORE SMALLINT=0,@ISLEMTIPINEGOREBAKIYEGRUPLA SMALLINT=0                   
 as                     
BEGIN            
            
declare @pIslemTipi nvarchar(250)            
declare @pBAKIYE1 money            
             
             
DECLARE @ACARI TABLE (ROWNUMBER INT,TARIH DATETIME, TESSIRNO INT, MUSNO INT, BAACIKLA nvarchar(14),ACIKLAMA nvarchar(200),                      
  ISLEMNO INT,DOVIZTUT float,DOVIZKODU nvarchar(2),OZELKOD nvarchar(3),ISLEMTIPI nvarchar(30),                      
  BELGENO nvarchar(10), ACIKLABAKIYE nvarchar(1), TP nvarchar(2), [Ort Vade] DATETIME,SaticiKodu nvarchar(15),                      
  SaticiAdi nvarchar(25), KULNO INT,KULADI nvarchar(20), DovizBorc float,                      
  DovizAlacak float,Aciklama2 nvarchar(200),                      
  SiraNo INT, CARINO INT, MUSKOD nvarchar(20),MUSADI nvarchar(50), IsIstasyonKodu nvarchar(30),                       
  IsIstasyonAdi nvarchar(30), TESLIM nvarchar(200),BORC money, ALACAK money,  FARK money,                       
  BAKIYE money,eFaturaNo varchar(30),eFaturaDurumu varchar(20),eFaturaGonderimTarihi datetime,OdemeBilgisi nvarchar(100),DovizKur float)                      
DECLARE @BAKIYE money, @IBKY MONEY,@BAKIYE2 money                      
SELECT  @IBKY= SUM(BORC-ALACAK)  FROM ACARI WHERE MUSNO=@MUSNO AND TARIH<=@ILKTARIH                      
SET @BAKIYE = 0                      
IF @IBKY IS NULL                      
     SET @IBKY=0          	 
                          
declare @Musteri table (MusteriNo decimal,UstMusteriNo decimal)                            
update ACARI SET AcikKapali='A' WHERE AcikKapali <>'K' and MUSNO = @MUSNO              
insert into @Musteri             
select distinct MUSNO,UstCariNo from AMUSTERI where UstCariNo = @MUSNO or MUSNO = @MUSNO
--select distinct MUSNO,UstCariNo from AMUSTERI where UstCariNo=@MUSNO    
              
IF @ISLEMTIPINEGORE=1            
BEGIN            
  INSERT INTO @ACARI (ROWNUMBER,TARIH,MUSNO,FARK,BAKIYE,BAACIKLA,ACIKLAMA,ISLEMNO) VALUES (0,@ILKTARIH,@MUSNO,@IBKY,0,'Devir','Hesap Ekstresi Devir Tutarı',1);            
            
INSERT INTO @ACARI            
SELECT ROW_NUMBER() OVER(ORDER BY ISLEMTIPI ASC,TARIH ASC,CARINO ASC) AS ROWNUMBER1,TARIH,TESSIRNO,MUSNO,BAACIKLA,    
(ISNULL(ACIKLAMA, '''')+ ' - - ' +ISNULL((select TOP 1 STDB.Ack1 FROM STOKHARDETBAG as STDB where STDB.IslemNo=ACARI.ISLEMNO),'')) as ACIKLAMA,            
    
 ISLEMNO,DOVIZTUT,DOVIZKODU,OZELKOD,ISLEMTIPI,             
  ISNULL(BELGENO, '''') as [BELGENO],ACIKLABAKIYE,TP,VadeTarihi as Ort_Vade,SaticiKodu,            
  SaticiAdi, KULNO, KULADI, DovizBorc,             
  DovizAlacak,Aciklama2,            
  SiraNo, CARINO, MUSKOD, MUSADI, IsIstasyonKodu,             
  IsIstasyonAdi,(select TeslimEden + ' - - ' + TeslimAlan from ACIKLAMA where FATURANO = ISLEMNO) as Teslim,            
  BORC money, ALACAK money,(BORC-ALACAK), NULL,             
  (select top 1 A.eFaturaNo  from STOKHARDETBAG as A where A.IslemNo=ACARI.ISLEMNO) eFaturaNo,                 
 (select top 1 A.eFaturaDurumu  from STOKHARDETBAG as A where A.IslemNo=ACARI.ISLEMNO) eFaturaDurumu,             
 (select top 1 A.eFaturaGonderimTarihi from STOKHARDETBAG as A where A.IslemNo=ACARI.ISLEMNO) eFaturaGonderimTarihi,          
 (select top 1 OdemeBilgisi from STOKHARDETBAG where IslemNo=ACARI.ISLEMNO ) as OdemeBilgisi,DovizKur           
 FROM ACARI             
 WHERE MUSNO in (select MusteriNo from @Musteri) AND TARIH >@ILKTARIH AND TARIH<@SONTARIH             
 and 1=               
 case  when @KAPALIHAREKET is not null then  case  when AcikKapali <> @KAPALIHAREKET then 1 else 0 end else 1 end              
 ORDER BY ROWNUMBER1 ASC             
            
             
 END             
 ELSE         
 BEGIN            
INSERT INTO @ACARI (ROWNUMBER,TARIH,MUSNO,FARK,BAKIYE,BAACIKLA,ACIKLAMA,ISLEMNO) VALUES (0,@ILKTARIH,@MUSNO,@IBKY,0,'Devir','Hesap Ekstresi Devir Tutarı',1)            
 INSERT INTO @ACARI          
 SELECT ROW_NUMBER() OVER(ORDER BY  TARIH,CARINO  ,CARINO ASC) AS ROWNUMBER,TARIH,TESSIRNO,MUSNO,BAACIKLA,    
     
(ISNULL(ACIKLAMA, '''')+ ' - - ' +ISNULL((select TOP 1 STDB.Ack1 FROM STOKHARDETBAG as STDB where STDB.IslemNo=ACARI.ISLEMNO),'')) as ACIKLAMA,         
    
  ISLEMNO,DOVIZTUT,DOVIZKODU,OZELKOD,ISLEMTIPI,             
  ISNULL(BELGENO, '''') as [BELGENO],ACIKLABAKIYE,TP,VadeTarihi as [Ort Vade],SaticiKodu,            
  SaticiAdi, KULNO, KULADI, DovizBorc,             
  DovizAlacak,Aciklama2,            
  SiraNo, CARINO, MUSKOD, MUSADI, IsIstasyonKodu,             
  IsIstasyonAdi,(select TeslimEden + ' - - ' + TeslimAlan from ACIKLAMA where FATURANO = ISLEMNO) as Teslim,            
  BORC money, ALACAK money,(BORC-ALACAK), NULL,             
  (select top 1 A.eFaturaNo  from STOKHARDETBAG as A where A.IslemNo=ACARI.ISLEMNO) eFaturaNo,                 
 (select top 1 A.eFaturaDurumu  from STOKHARDETBAG as A where A.IslemNo=ACARI.ISLEMNO) eFaturaDurumu,             
 (select top 1 A.eFaturaGonderimTarihi from STOKHARDETBAG as A where A.IslemNo=ACARI.ISLEMNO) eFaturaGonderimTarihi,          
 (select top 1 OdemeBilgisi from STOKHARDETBAG where IslemNo=ACARI.ISLEMNO ) as OdemeBilgisi,DovizKur          
 FROM ACARI             
 WHERE MUSNO in (select MusteriNo from @Musteri)  AND TARIH >@ILKTARIH AND TARIH<@SONTARIH             
 and 1=               
 case  when @KAPALIHAREKET is not null then  case  when AcikKapali <> @KAPALIHAREKET then 1 else 0 end else 1 end              
 ORDER BY ROWNUMBER ASC             
            
 END            
            
END              
        
declare @ROWNUMBER INT            
declare @IslemTipi1 varchar(250)            
            
declare AcariCursor cursor             
for Select ROWNUMBER,ISLEMTIPI FROM  @ACARI ORDER BY ROWNUMBER ASC             
FOR UPDATE OF BAKIYE OPEN AcariCursor            
FETCH NEXT FROM AcariCursor INTO @ROWNUMBER,@IslemTipi1            
WHILE @@FETCH_STATUS=0            
BEGIN             
            
IF @ISLEMTIPINEGORE=0             
BEGIN            
 SET @BAKIYE2=(SELECT SUM(ISNULL(FARK,0)) FROM @ACARI  WHERE ROWNUMBER<=@ROWNUMBER )            
 UPDATE TOP(1) @ACARI SET BAKIYE=@BAKIYE2 WHERE ROWNUMBER=@ROWNUMBER            
            
end  else            
begin            
            
if @ROWNUMBER=0            
 set @pIslemTipi=@IslemTipi1;            
            
   if @pIslemTipi=@IslemTipi1            
   begin            
    SET @BAKIYE2=(SELECT SUM(ISNULL(FARK,0)) FROM @ACARI  WHERE ROWNUMBER<=@ROWNUMBER and ISLEMTIPI=@pIslemTipi)            
    UPDATE TOP(1) @ACARI SET BAKIYE=@BAKIYE2 WHERE ROWNUMBER=@ROWNUMBER            
   end            
   else             
   begin            
    set @pIslemTipi=@IslemTipi1;            
    SET @BAKIYE2=(SELECT SUM(ISNULL(FARK,0)) FROM @ACARI  WHERE ROWNUMBER<=@ROWNUMBER and ISLEMTIPI=@pIslemTipi)            
    UPDATE TOP(1) @ACARI SET BAKIYE=@BAKIYE2 WHERE ROWNUMBER=@ROWNUMBER            
   end            
end            
            
 FETCH NEXT FROM AcariCursor INTO @ROWNUMBER,@IslemTipi1            
END            
CLOSE AcariCursor             
DEALLOCATE AcariCursor            
            
if @ISLEMTIPINEGOREBAKIYEGRUPLA=0            
SELECT  * FROM @ACARI  ORDER BY ROWNUMBER            
else            
SELECT  ISLEMTIPI,sum(BORC) as BORC,sum(ALACAK) as ALACAK,sum(BORC-ALACAK) as BAKIYE FROM @ACARI            
where ISLEMTIPI is not null and MUSNO=@MUSNO  GROUP BY ISLEMTIPI     
go--
 IF NOT EXISTS (SELECT *  FROM sys.tables WHERE  name='GridSetting')
 BEGIN 



