-- Tabele, trigeri, pogledi u procedure za Pos kasu
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS(SELECT * FROM sys.columns WHERE [object_id] = object_id('dbo.Artikli') AND name = 'PluFP')
BEGIN
	ALTER TABLE dbo.Artikli ADD 
		[TipVelicine] [varchar](10) NULL,
		[Velicina] [varchar](10) NULL,
		[Boja] [varchar](20) NULL,
		[ProizvodjacIme] [nvarchar](50) NULL,
		[Brend] [nvarchar](20) NULL,
		[ZemljaUvoza] [nvarchar](30) NULL,
		[PluFP] [int] IDENTITY(100,1) NOT NULL
END
IF NOT EXISTS(SELECT * FROM sys.columns WHERE [object_id] = object_id('dbo.Artikli') AND name = 'TipVelicine')
BEGIN
	ALTER TABLE dbo.Artikli ADD 
		[TipVelicine] [varchar](10) NULL,
		[Velicina] [varchar](10) NULL,
		[Boja] [varchar](20) NULL
END
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Artikli]') AND name = N'IX_ArtikliBarkod')
CREATE NONCLUSTERED INDEX [IX_ArtikliBarkod] ON [dbo].[Artikli] 
(
	[Barkod] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Artikli]') AND name = N'IX_ArtikliPluFP')
CREATE NONCLUSTERED INDEX [IX_ArtikliPluFP] ON [dbo].[Artikli] 
(
	[PluFP] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

GO
SET ANSI_NULLS ON
GO
-- TABELE
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArhivaZaPos]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ArhivaZaPos](
	[Objekat] [nvarchar](3) NOT NULL,
	[ID] [nvarchar](10) NOT NULL,
	[Bar_cod] [nvarchar](13) NULL,
	[PLU_Naziv] [nvarchar](25) NULL,
	[Cena] [money] NULL,
	[Tarifa] [nvarchar](1) NULL,
	[Ind_deckol] [nvarchar](1) NULL,
	[Ind_otv] [nvarchar](1) NULL,
	[Ind_bottle] [nvarchar](1) NULL,
	[Kau_id] [nvarchar](10) NULL,
	[Unos_l] [nvarchar](1) NULL,
 CONSTRAINT [aaaaaArhivaZaPos_PK] PRIMARY KEY NONCLUSTERED 
(
	[Objekat] ASC,
	[ID] 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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArhivaZaPOSDnevnik]') AND type in (N'U'))
BEGIN
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArhivaZaPOSDnevnik]') AND type in (N'U'))
DROP TABLE [dbo].[ArhivaZaPOSDnevnik]
GO

CREATE TABLE [dbo].[ArhivaZaPOSDnevnik](
	[IDPos] [int] NOT NULL,
	[Datum] [datetime] NULL,
	[Sifra] [int] NOT NULL,
	[RedBroj] [int] IDENTITY(1,1) NOT NULL,
	[Unos_L] [varchar](1) NULL,
	[StCena] [numeric](10, 2) NULL,
	[Cena] [numeric](10, 2) NULL,
	[Broj] [int] NULL,
	[Promena] [smallint] NULL,
 CONSTRAINT [PK_ArhZaPosDnevnik] PRIMARY KEY CLUSTERED 
(
	[IDPos] ASC,
	[Sifra] ASC,
	[RedBroj] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliFP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ArtikliFP](
	[Sifra] [int] NOT NULL,
	[Artikal] [nvarchar](13) NULL,
	[NazivArtikla] [nvarchar](50) NULL,
	[JM] [nvarchar](3) NULL,
	[Tarifa] [nvarchar](4) NULL,
	[Cena] [numeric](8, 2) NULL,
	[Barkod] [nvarchar](13) NULL,
	[PLU] [int] NULL,
	[Zalihe] [numeric](8, 2) NULL,
	[Marker] [bit] NOT NULL,
	[SlobodnaCena] [bit] NOT NULL,
	[Decimale] [bit] NOT NULL,
	[Kategorija] [int] NULL,
	[Rabat] [decimal](5, 2) NULL,
	[Unos_L] [nvarchar](1) NULL,
	[PluVaga] [int] NULL,
	[Tip] [smallint] NULL,
 CONSTRAINT [PK_ArtikliFp] PRIMARY KEY CLUSTERED 
(
	[Sifra] 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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliPlu]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ArtikliPlu](
	[Sifra] [int] NOT NULL,
	[Plu] [int] IDENTITY(30000,1) NOT NULL,
 CONSTRAINT [PK_ArtikliPlu] PRIMARY KEY CLUSTERED 
(
	[Sifra] 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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Boniteti]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Boniteti](
	[Partner] [nvarchar](8) NOT NULL,
	[Bonitet] [int] NULL,
	[Popust] [smallmoney] NULL,
 CONSTRAINT [PK_Boniteti] PRIMARY KEY CLUSTERED 
(
	[Partner] 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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Depozit]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Depozit](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Kasa] nvarchar(3) NULL,
	[Datum] [datetime] NULL,
	[Ulaz] [money] NULL,
	[Izlaz] [money] NULL,
	[Opis] [nvarchar](20) NULL,
	[Operater] [nvarchar](3) NULL,
 CONSTRAINT [aaaaaDepozit_PK] PRIMARY KEY NONCLUSTERED 
(
	[ID] 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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KasaFP]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[KasaFP](
	[Broj] [int] NOT NULL,
	[Dokument] [nvarchar](10) NULL,
	[Datum] [smalldatetime] NULL,
	[Iznos] [numeric](10, 2) NULL,
	[IznosPDV] [numeric](10, 2) NULL,
	[Placanje] [int] NULL,
	[Promena] [int] NULL,
	[Partner] [nvarchar](8) NULL,
	[Valuta] [smalldatetime] NULL,
	[Protokol] [int] NULL,
	[Knjizeno] [bit] NOT NULL,
	[ok] [bit] NOT NULL,
	[Operater] [smallint] NULL,
	[Objekat] [varchar](3) NULL,
	[Kasa] [varchar](3) NULL,
	[Zakljucenje] [smallint] NULL,
	[SysDatum] [smalldatetime] NULL,
	[Iznos2] [numeric](10, 2) NULL,
	[Gotovina] [numeric](10, 2) NULL,
	[Kartica] [numeric](10, 2) NULL,
	[Racun] [numeric](10, 2) NULL,
	[Kredit] [numeric](10, 2) NULL,
	[Opis] [nvarchar](60) NULL,
	[Faktura] [varchar](15) NULL,
	[BrojKartice] [varchar](20) NULL,
	[ExterniBroj] [int] NULL,
	[ExterniPromena] [smallint] NULL,
	[KasaABroj] [int] NULL,
	[CardID] [smallint] NULL,
	[PosTerminal] [smallint] NULL,
	[Zamena] [bit] NULL,
	[Povrat] [bit] NULL,
	[BrojRata] [smallint] NULL,
	[PopustNaRacun] [numeric](10,2) NULL,
	[PartnerPopust] [varchar](8) NULL,
	[PoslatNaFP] [bit] NULL,
	[ZakljucenDan] [bit] NULL,
	[Stornirano] [bit] NULL,
	[ValidacijaID] [int] NULL,
	[Poslato] [bit] NULL,
	[LastEditDate] [smalldatetime] NULL,
	[CreationDate] [smalldatetime] NULL,
 CONSTRAINT [PK_KasaFP] PRIMARY KEY CLUSTERED 
(
	[Broj] 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  NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.KasaFP') AND name = 'BrojKartice')
BEGIN
	ALTER TABLE dbo.KasaFP ADD [BrojKartice] [varchar](20) NULL
END
SET ANSI_PADDING OFF
GO

IF  NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.KasaFP') AND name = 'PosTerminal')
BEGIN
	ALTER TABLE dbo.KasaFP ADD [PosTerminal] [smallint] NULL,
		[Zamena] [bit] NULL,
		[Povrat] [bit] NULL,
		[BrojRata] [smallint] NULL,
		[PopustNaRacun] [numeric](10,2) NULL,
		[PartnerPopust] varchar(8) NULL,
		[Stornirano] [bit] NULL,
		[ValidacijaID] [int] NULL,
		[Poslato] [bit] NULL;
END
SET ANSI_PADDING OFF
GO
IF  NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.KasaFP') AND name = 'Stornirano')
BEGIN
	ALTER TABLE dbo.KasaFP ADD [Stornirano] [bit] NULL, [ValidacijaID] [int] NULL, [Poslato] [bit] NULL
END
SET ANSI_PADDING OFF
GO

UPDATE dbo.KasaFP SET Zamena = 0, Povrat = 0 WHERE Zamena IS NULL

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KasaFP_Tombstone]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[KasaFP_Tombstone](
	[Broj] [int] NOT NULL,
	[DeletionDate] [datetime] NULL,
 CONSTRAINT [PKDEL_KasaFP_Tombstone_Broj] PRIMARY KEY CLUSTERED 
(
	[Broj] 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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KasaFPSt]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[KasaFPSt](
	[Broj] [int] NOT NULL,
	[RedBroj] [int] NOT NULL,
	[Sifra] [int] NOT NULL,
	[Kolicina] [numeric](8, 3) NULL,
	[Cena] [numeric](8, 2) NULL,
	[Rabat] [numeric](5, 2) NULL,
	[TarifaA] [varchar](1) NULL,
	[Stopa] [numeric](4, 1) NULL,
	[Operater] [int] NULL,
	[Storno] [bit] NULL,
	[Kasa] [varchar](3) NULL,
	[Zakljucenje] [smallint] NULL,
	[LastEditDate] [datetime] NULL,
	[CreationDate] [datetime] NULL,
 CONSTRAINT [PK_KasaFPSt] PRIMARY KEY CLUSTERED 
(
	[Broj] ASC,
	[RedBroj] 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

SET ANSI_PADDING OFF
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KasaFPSt_Tombstone]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[KasaFPSt_Tombstone](
	[Broj] [int] NOT NULL,
	[RedBroj] [int] NOT NULL,
	[DeletionDate] [datetime] NULL,
 CONSTRAINT [PKDEL_KasaFPSt_Tombstone_BrojRedBroj] PRIMARY KEY CLUSTERED 
(
	[Broj] ASC,
	[RedBroj] 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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Korisnici]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Korisnici](
	[RBr] [int] NOT NULL,
	[Korisnik] [nvarchar](20) NULL,
	[Lozinka] [nvarchar](20) NULL,
	[Ime] [nvarchar](50) NULL,
	[LastLogIn] [datetime] NULL,
	[LastLogOut] [datetime] NULL,
	[ID] [nvarchar](10) NULL,
	[Adresa] [nvarchar](50) NULL,
	[Nivo] [smallint] NULL,
	[Aktivan] [bit] NOT NULL,
 CONSTRAINT [aaaaaKorisnici_PK] PRIMARY KEY NONCLUSTERED 
(
	[RBr] 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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PL_PosTerminali]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[PL_PosTerminali](
	[PosTerminal] [smallint] NOT NULL,
	[Banka] [nvarchar](30) NULL,
	[Partner] [nvarchar](8) NULL,
	[Aktivan] [bit] NULL,
 CONSTRAINT [PK_PLPosTerminali] PRIMARY KEY CLUSTERED 
(
	[PosTerminal] 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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PLKartice]') AND type in (N'U'))
	DROP TABLE [dbo].[PLKartice]
CREATE TABLE [dbo].[PLKartice](
	[PosTerminal] [smallint] NOT NULL,
	[CardID] [smallint] NOT NULL,
	[Naziv] [nvarchar](30) NULL,
	[Partner] [nvarchar](8) NULL,
	[Provizija] [numeric](5, 2) NULL,
 CONSTRAINT [PK_PLKartice_1] PRIMARY KEY CLUSTERED 
(
	[PosTerminal] ASC,
	[CardID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PopisTerm]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[PopisTerm](
	[Term] [varchar](3) NOT NULL,
	[PopisID] [int] NOT NULL,
	[Sifra] [int] NOT NULL,
	[Kolicina] [numeric](10, 3) NOT NULL,
	[Cena] [numeric](9, 2) NOT NULL,
	[Opis] [nvarchar](50) NULL,
	[Barkod] [varchar](13) NULL,
	[Datum] [smalldatetime] NULL,
	[Lista] [int] NULL,
	[Prenet] [bit] NULL,
	[DatumTerm] [smalldatetime] NULL,
	[SysDatum] [smalldatetime] NULL,
	[Objekat] [varchar](3) NULL,
	[Tabela] [varchar](15) NULL,
	[Dokument] [varchar](20) NULL,
	[Ocitavanje] [varchar](20) NULL,
	[FakCena] [numeric](10, 3) NULL,
	[Rabat] [numeric](6, 3) NULL,
	[Tarifa] [varchar](4) NULL,
	[Stopa] [numeric](5, 2) NULL,
	[Promena] [smallint] NULL,
	[Broj] [int] NULL,
 CONSTRAINT [PK_PopisTerm] PRIMARY KEY CLUSTERED 
(
	[Term] ASC,
	[PopisID] 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

SET ANSI_PADDING OFF
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RekDanKase]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RekDanKase](
	[IDPaz] [int] IDENTITY(1,1) NOT NULL,
	[Datum] [datetime] NULL,
	[Objekat] [nvarchar](3) NULL,
	[Kasa] [nvarchar](3) NOT NULL,
	[Partner] [nvarchar](8) NULL,
	[Dokument] [nvarchar](10) NOT NULL,
	[Placanje] [smallint] NULL,
	[VrstaPlacanja] [nvarchar](20) NULL,
	[Kartica] [nvarchar](30) NULL,
	[IznosA] [money] NULL,
	[PorezA] [money] NULL,
	[PopustA] [money] NULL,
	[IznosB] [money] NULL,
	[PorezB] [money] NULL,
	[PopustB] [money] NULL,
	[IznosC] [money] NULL,
	[PorezC] [money] NULL,
	[PopustC] [money] NULL,
	[Svega] [money] NULL,
	[Iznos2] [money] NULL,
	[IznosTr] [money] NULL,
	[Broj] [int] NULL,
 CONSTRAINT [PK_RekDanKase] PRIMARY KEY CLUSTERED 
(
	[IDPaz] 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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING OFF
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Velicine]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Velicine](
	[TipVelicine] [varchar](10) NOT NULL,
	[Velicina] [varchar](10) NOT NULL,
	[Sifra] [tinyint] NULL,
 CONSTRAINT [PK_Velicine_1] PRIMARY KEY CLUSTERED 
(
	[TipVelicine] ASC,
	[Velicina] 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

SET ANSI_PADDING OFF
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[zaKasuPOS]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[zaKasuPOS](
	[Objekat] [nvarchar](3) NOT NULL,
	[ID] [nvarchar](10) NOT NULL,
	[Bar_cod] [nvarchar](14) NULL,
	[PLU_Naziv] [nvarchar](25) NULL,
	[Cena] [money] NULL,
	[Tarifa] [nvarchar](1) NULL,
	[Ind_deckol] [nvarchar](1) NULL,
	[Ind_otv] [nvarchar](1) NULL,
	[Ind_bottle] [nvarchar](1) NULL,
	[Kau_id] [nvarchar](10) NULL,
	[Unos_l] [nvarchar](1) NULL,
 CONSTRAINT [aaaaazaKasuPOS_PK] PRIMARY KEY NONCLUSTERED 
(
	[Objekat] ASC,
	[ID] 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 NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[zaKasuPOS]') AND name = N'Bar_cod')
CREATE NONCLUSTERED INDEX [Bar_cod] ON [dbo].[zaKasuPOS] 
(
	[Bar_cod] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[zaKasuPOS]') AND name = N'IX_zaKasuPOS')
CREATE NONCLUSTERED INDEX [IX_zaKasuPOS] ON [dbo].[zaKasuPOS] 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[zaKasuPOS]') AND name = N'Kau_id')
CREATE NONCLUSTERED INDEX [Kau_id] ON [dbo].[zaKasuPOS] 
(
	[Kau_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Zakljucenja]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Zakljucenja](
	[Objekat] [nvarchar](3) NOT NULL,
	[Kasa] [nvarchar](3) NOT NULL,
	[Datum] [smalldatetime] NOT NULL,
	[Zakljucenje] [int] NOT NULL,
	[Total] [money] NULL,
	[TaxA] [money] NULL,
	[TaxB] [money] NULL,
	[TaxC] [money] NULL,
	[TaxD] [money] NULL,
	[TaxE] [money] NULL,
	[TaxF] [money] NULL,
	[TaxG] [money] NULL,
	[TaxH] [money] NULL,
	[PosSerijskiBroj] [nvarchar](12) NULL,
	[PosFM] [nvarchar](12) NULL,
	[SisDatum] [smalldatetime] NULL,
	[BrRacuna] [int] NULL,
	[BrPopusta] [int] NULL,
	[Popusti] [money] NULL,
	[BrStorna] [int] NULL,
	[Storna] [money] NULL,
	[BrArtikala] [int] NULL,
	[BrProdaja] [int] NULL,
	[Gotovina] [money] NULL,
	[Cek] [money] NULL,
	[Kartice] [money] NULL,
	[Kredit] [money] NULL,
 CONSTRAINT [PK_Zakljucenja] PRIMARY KEY CLUSTERED 
(
	[Objekat] ASC,
	[Kasa] ASC,
	[Datum] ASC,
	[Zakljucenje] 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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[trgArtikliFPInsert]'))
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Dejan
-- Create date: 9.11.2009
-- Description:	Azuraira PLU za novi uneti artikal u tabelu ArtikliFP
-- =============================================
CREATE TRIGGER [dbo].[trgArtikliFPInsert] 
   ON  [dbo].[ArtikliFP] 
   AFTER INSERT
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	insert into ArtikliPlu (Sifra) 
		Select i.Sifra from Inserted i 
		where not i.Sifra in (Select Sifra from ArtikliPlu) AND ((i.Plu is null) or (i.Plu = 0))
		Order by i.Sifra
	update ArtikliFP set ArtikliFP.Plu = a.Plu 
		From ArtikliPlu a inner join inserted i on a.Sifra = i.Sifra
		where ArtikliFP.Sifra = a.Sifra and ((ArtikliFP.Plu is null) or (ArtikliFP.Plu = 0))

END

' 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[KasaFP_DeletionTrigger]'))
EXEC dbo.sp_executesql @statement = N'CREATE TRIGGER [dbo].[KasaFP_DeletionTrigger] 
    ON [dbo].[KasaFP] 
    AFTER DELETE 
AS 
SET NOCOUNT ON 
UPDATE [dbo].[KasaFP_Tombstone] 
    SET [DeletionDate] = GETDATE() 
    FROM deleted 
    WHERE deleted.[Broj] = [dbo].[KasaFP_Tombstone].[Broj] 
IF @@ROWCOUNT = 0 
BEGIN 
    INSERT INTO [dbo].[KasaFP_Tombstone] 
    ([Broj], DeletionDate)
    SELECT [Broj], GETDATE()
    FROM deleted 
END
' 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[KasaFP_InsertTrigger]'))
EXEC dbo.sp_executesql @statement = N'CREATE TRIGGER [dbo].[KasaFP_InsertTrigger] 
    ON [dbo].[KasaFP] 
    AFTER INSERT 
AS 
BEGIN 
    SET NOCOUNT ON 
    UPDATE [dbo].[KasaFP] 
    SET [CreationDate] = GETDATE() 
    FROM inserted 
    WHERE inserted.[Broj] = [dbo].[KasaFP].[Broj] 
END;
' 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[KasaFP_UpdateTrigger]'))
EXEC dbo.sp_executesql @statement = N'CREATE TRIGGER [dbo].[KasaFP_UpdateTrigger] 
    ON [dbo].[KasaFP] 
    AFTER UPDATE 
AS 
BEGIN 
    SET NOCOUNT ON 
    UPDATE [dbo].[KasaFP] 
    SET [LastEditDate] = GETDATE() 
    FROM inserted 
    WHERE inserted.[Broj] = [dbo].[KasaFP].[Broj] 
    -- Markiraj u stavkama broj kase, zaključenje i operatera
    -- kad se ažirira polje PoslatNaFP
	IF UPDATE(PoslatNaFP)
	BEGIN
		UPDATE dbo.KasaFPSt SET 
			Kasa = z.Kasa
			, Zakljucenje = z.Zakljucenje 
			, Operater = z.Operater
		FROM inserted z 
		WHERE z.Broj = dbo.KasaFPSt.Broj;    
		
		BEGIN TRY
			UPDATE dbo.ArtikliFP SET Zalihe = Zalihe - t.kol
			FROM (SELECT Sifra, SUM(Kolicina) kol FROM dbo.KasaFPSt 
					WHERE  Broj IN (SELECT broj FROM INSERTED i) GROUP BY Sifra) t
				WHERE dbo.ArtikliFP.Sifra = t.Sifra
		END TRY
		BEGIN CATCH
		
		END CATCH
	END
END;
' 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[KasaFPSt_DeletionTrigger]'))
EXEC dbo.sp_executesql @statement = N'
CREATE TRIGGER [dbo].[KasaFPSt_DeletionTrigger] 
    ON [dbo].[KasaFPSt] 
    AFTER DELETE 
AS 
SET NOCOUNT ON 
UPDATE [dbo].[KasaFPSt_Tombstone] 
    SET [DeletionDate] = GETDATE() 
    FROM deleted 
    WHERE deleted.[Broj] = [dbo].[KasaFPSt_Tombstone].[Broj] 
    AND deleted.[RedBroj] = [dbo].[KasaFPSt_Tombstone].[RedBroj] 
IF @@ROWCOUNT = 0 
BEGIN 
    INSERT INTO [dbo].[KasaFPSt_Tombstone] 
    ([Broj], [RedBroj], DeletionDate)
    SELECT [Broj], [RedBroj], GETDATE()
    FROM deleted 
END

' 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[KasaFPSt_InsertTrigger]'))
EXEC dbo.sp_executesql @statement = N'
CREATE TRIGGER [dbo].[KasaFPSt_InsertTrigger] 
    ON [dbo].[KasaFPSt] 
    AFTER INSERT 
AS 
BEGIN 
    SET NOCOUNT ON 
    UPDATE [dbo].[KasaFPSt] 
    SET [CreationDate] = GETDATE() 
    FROM inserted 
    WHERE inserted.[Broj] = [dbo].[KasaFPSt].[Broj] 
    AND inserted.[RedBroj] = [dbo].[KasaFPSt].[RedBroj] 
END;

' 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[KasaFPSt_UpdateTrigger]'))
EXEC dbo.sp_executesql @statement = N'
CREATE TRIGGER [dbo].[KasaFPSt_UpdateTrigger] 
    ON [dbo].[KasaFPSt] 
    AFTER UPDATE 
AS 
BEGIN 
    SET NOCOUNT ON 
    UPDATE [dbo].[KasaFPSt] 
    SET [LastEditDate] = GETDATE() 
    FROM inserted 
    WHERE inserted.[Broj] = [dbo].[KasaFPSt].[Broj] 
    AND inserted.[RedBroj] = [dbo].[KasaFPSt].[RedBroj] 
END;

' 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArhivaZaPo__Cena__69FBBC1F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArhivaZaPos] ADD  CONSTRAINT [DF__ArhivaZaPo__Cena__69FBBC1F]  DEFAULT ((0)) FOR [Cena]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArhivaZaP__Tarif__6AEFE058]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArhivaZaPos] ADD  CONSTRAINT [DF__ArhivaZaP__Tarif__6AEFE058]  DEFAULT ('A') FOR [Tarifa]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArhivaZaP__Ind_d__6BE40491]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArhivaZaPos] ADD  CONSTRAINT [DF__ArhivaZaP__Ind_d__6BE40491]  DEFAULT ('N') FOR [Ind_deckol]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArhivaZaP__Ind_o__6CD828CA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArhivaZaPos] ADD  CONSTRAINT [DF__ArhivaZaP__Ind_o__6CD828CA]  DEFAULT ('N') FOR [Ind_otv]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArhivaZaP__Ind_b__6DCC4D03]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArhivaZaPos] ADD  CONSTRAINT [DF__ArhivaZaP__Ind_b__6DCC4D03]  DEFAULT ('N') FOR [Ind_bottle]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArhivaZaP__Unos___6EC0713C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArhivaZaPos] ADD  CONSTRAINT [DF__ArhivaZaP__Unos___6EC0713C]  DEFAULT ('N') FOR [Unos_l]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArtikliFP__JM__27E3DFFF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArtikliFP] ADD  DEFAULT ('kom') FOR [JM]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArtikliFP__Tarif__28D80438]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArtikliFP] ADD  DEFAULT ('A') FOR [Tarifa]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArtikliFP__Cena__29CC2871]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArtikliFP] ADD  DEFAULT ((0)) FOR [Cena]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArtikliFP__Zalih__2AC04CAA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArtikliFP] ADD  DEFAULT ((0)) FOR [Zalihe]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArtikliFP__Marke__2BB470E3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArtikliFP] ADD  DEFAULT ((1)) FOR [Marker]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArtikliFP__Slobo__2CA8951C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArtikliFP] ADD  DEFAULT ((1)) FOR [SlobodnaCena]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArtikliFP__Decim__2D9CB955]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArtikliFP] ADD  DEFAULT ((1)) FOR [Decimale]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArtikliFP__Kateg__2E90DD8E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArtikliFP] ADD  DEFAULT ((0)) FOR [Kategorija]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArtikliFP__Rabat__2F8501C7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArtikliFP] ADD  DEFAULT ((0)) FOR [Rabat]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__ArtikliFP__Unos___30792600]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[ArtikliFP] ADD  DEFAULT ('N') FOR [Unos_L]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Depozit__Datum__2E1BDC42]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Depozit] ADD  CONSTRAINT [DF__Depozit__Datum__2E1BDC42]  DEFAULT (getdate()) FOR [Datum]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Depozit__Ulaz__2F10007B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Depozit] ADD  CONSTRAINT [DF__Depozit__Ulaz__2F10007B]  DEFAULT ((0)) FOR [Ulaz]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Depozit__Izlaz__300424B4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Depozit] ADD  CONSTRAINT [DF__Depozit__Izlaz__300424B4]  DEFAULT ((0)) FOR [Izlaz]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__Iznos__453F38BC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__Iznos__453F38BC]  DEFAULT ((0)) FOR [Iznos]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__IznosPDV__46335CF5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__IznosPDV__46335CF5]  DEFAULT ((0)) FOR [IznosPDV]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__Placanje__4727812E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__Placanje__4727812E]  DEFAULT ((1)) FOR [Placanje]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__Promena__481BA567]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__Promena__481BA567]  DEFAULT ((211)) FOR [Promena]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFP_Knjizeno]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF_KasaFP_Knjizeno]  DEFAULT ((0)) FOR [Knjizeno]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__ok__490FC9A0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__ok__490FC9A0]  DEFAULT ((0)) FOR [ok]
END

GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__Zamena]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__Zamena]  DEFAULT ((0)) FOR [Zamena]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__BrojRata]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__BrojRata]  DEFAULT ((0)) FOR [BrojRata]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__PopustNaRacun]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__PopustNaRacun]  DEFAULT ((0)) FOR [PopustNaRacun]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__Operater__4A03EDD9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__Operater__4A03EDD9]  DEFAULT ((0)) FOR [Operater]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__Objekat__4AF81212]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__Objekat__4AF81212]  DEFAULT ('1') FOR [Objekat]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__Zakljuce__4BEC364B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__Zakljuce__4BEC364B]  DEFAULT ((0)) FOR [Zakljucenje]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFP_SysDatum]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF_KasaFP_SysDatum]  DEFAULT (getdate()) FOR [SysDatum]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__Iznos2__4CE05A84]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__Iznos2__4CE05A84]  DEFAULT ((0)) FOR [Iznos2]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__Gotovina__4DD47EBD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__Gotovina__4DD47EBD]  DEFAULT ((0)) FOR [Gotovina]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__Kartica__4EC8A2F6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__Kartica__4EC8A2F6]  DEFAULT ((0)) FOR [Kartica]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__Racun__4FBCC72F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__Racun__4FBCC72F]  DEFAULT ((0)) FOR [Racun]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFP__Kredit__50B0EB68]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF__KasaFP__Kredit__50B0EB68]  DEFAULT ((0)) FOR [Kredit]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFP_PoslatNaFP]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF_KasaFP_PoslatNaFP]  DEFAULT ((0)) FOR [PoslatNaFP]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFP_ZakljucenDan]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF_KasaFP_ZakljucenDan]  DEFAULT ((0)) FOR [ZakljucenDan]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFP_LastEditDate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF_KasaFP_LastEditDate]  DEFAULT (GETDATE()) FOR [LastEditDate]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFP_CreationDate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF_KasaFP_CreationDate]  DEFAULT (GETDATE()) FOR [CreationDate]
END

GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFP_Stornirano]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF_KasaFP_Stornirano]  DEFAULT (0) FOR [Stornirano]
END

GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFP_Poslato]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFP] ADD  CONSTRAINT [DF_KasaFP_Poslato]  DEFAULT (0) FOR [Poslato]
END

GO


IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_KasaFPSt_KasaFP]') AND parent_object_id = OBJECT_ID(N'[dbo].[KasaFPSt]'))
ALTER TABLE [dbo].[KasaFPSt]  WITH CHECK ADD  CONSTRAINT [FK_KasaFPSt_KasaFP] FOREIGN KEY([Broj])
REFERENCES [dbo].[KasaFP] ([Broj])
ON UPDATE CASCADE
ON DELETE CASCADE
GO

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_KasaFPSt_KasaFP]') AND parent_object_id = OBJECT_ID(N'[dbo].[KasaFPSt]'))
ALTER TABLE [dbo].[KasaFPSt] CHECK CONSTRAINT [FK_KasaFPSt_KasaFP]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFPSt__Kolici__538D5813]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFPSt] ADD  CONSTRAINT [DF__KasaFPSt__Kolici__538D5813]  DEFAULT ((0)) FOR [Kolicina]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFPSt__Cena__54817C4C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFPSt] ADD  CONSTRAINT [DF__KasaFPSt__Cena__54817C4C]  DEFAULT ((0)) FOR [Cena]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFPSt__Rabat__5575A085]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFPSt] ADD  CONSTRAINT [DF__KasaFPSt__Rabat__5575A085]  DEFAULT ((0)) FOR [Rabat]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFPSt__Tarifa__5669C4BE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFPSt] ADD  CONSTRAINT [DF__KasaFPSt__Tarifa__5669C4BE]  DEFAULT ('A') FOR [TarifaA]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__KasaFPSt__Stopa__575DE8F7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFPSt] ADD  CONSTRAINT [DF__KasaFPSt__Stopa__575DE8F7]  DEFAULT ((17)) FOR [Stopa]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFPSt_Operater]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFPSt] ADD  CONSTRAINT [DF_KasaFPSt_Operater]  DEFAULT ((0)) FOR [Operater]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFPSt_Storno]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFPSt] ADD  CONSTRAINT [DF_KasaFPSt_Storno]  DEFAULT ((0)) FOR [Storno]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFPSt_Zakljucenje]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFPSt] ADD  CONSTRAINT [DF_KasaFPSt_Zakljucenje]  DEFAULT ((0)) FOR [Zakljucenje]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFPSt_LastEditDate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFPSt] ADD  CONSTRAINT [DF_KasaFPSt_LastEditDate]  DEFAULT (GETDATE()) FOR [LastEditDate]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_KasaFPSt_CreationDate]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[KasaFPSt] ADD  CONSTRAINT [DF_KasaFPSt_CreationDate]  DEFAULT (GETDATE()) FOR [CreationDate]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Korisnici__RBr__02FC7413]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Korisnici] ADD  CONSTRAINT [DF__Korisnici__RBr__02FC7413]  DEFAULT ((0)) FOR [RBr]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Korisnici__Nivo__03F0984C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Korisnici] ADD  CONSTRAINT [DF__Korisnici__Nivo__03F0984C]  DEFAULT ((0)) FOR [Nivo]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Korisnici__Aktiv__04E4BC85]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Korisnici] ADD  CONSTRAINT [DF__Korisnici__Aktiv__04E4BC85]  DEFAULT ((0)) FOR [Aktivan]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_PLPosTerminali_Aktivan]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[PL_PosTerminali] ADD  CONSTRAINT [DF_PLPosTerminali_Aktivan]  DEFAULT ((1)) FOR [Aktivan]
END

GO

IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_PLKartice_PLPosTerminali]') AND parent_object_id = OBJECT_ID(N'[dbo].[PLKartice]'))
ALTER TABLE [dbo].[PLKartice]  WITH CHECK ADD  CONSTRAINT [FK_PLKartice_PLPosTerminali] FOREIGN KEY([PosTerminal])
REFERENCES [dbo].[PL_PosTerminali] ([PosTerminal])
ON UPDATE CASCADE
ON DELETE CASCADE
GO

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_PLKartice_PLPosTerminali]') AND parent_object_id = OBJECT_ID(N'[dbo].[PLKartice]'))
ALTER TABLE [dbo].[PLKartice] CHECK CONSTRAINT [FK_PLKartice_PLPosTerminali]
GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_PLKartice_PosTerminal]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[PLKartice] ADD  CONSTRAINT [DF_PLKartice_PosTerminal]  DEFAULT ((1)) FOR [PosTerminal]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_PLKartice_Partner]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[PLKartice] ADD  CONSTRAINT [DF_PLKartice_Partner]  DEFAULT (N'K000') FOR [Partner]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_PLKartice_Provizija]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[PLKartice] ADD  CONSTRAINT [DF_PLKartice_Provizija]  DEFAULT ((3)) FOR [Provizija]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Popis_Kolicina]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_Popis_Kolicina]  DEFAULT ((0)) FOR [Kolicina]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_PopisTerm_Cena]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_Cena]  DEFAULT ((0)) FOR [Cena]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_PopisTerm_SysDatum]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_SysDatum]  DEFAULT (CONVERT([datetime],CONVERT([varchar],getdate(),(1)),(1))) FOR [Datum]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_PopisTerm_Lista]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_Lista]  DEFAULT ((1)) FOR [Lista]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_PopisTerm_Prenet]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_Prenet]  DEFAULT ((0)) FOR [Prenet]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_PopisTerm_SysDatum_1]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_SysDatum_1]  DEFAULT (getdate()) FOR [SysDatum]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_PopisTerm_Dokument]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_Dokument]  DEFAULT (N'0001') FOR [Dokument]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_PopisTerm_Promena]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_Promena]  DEFAULT ((125)) FOR [Promena]
END

GO


IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Velicine_Sifra]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Velicine] ADD  CONSTRAINT [DF_Velicine_Sifra]  DEFAULT ((0)) FOR [Sifra]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__zaKasuPOS__Cena__1AF3F935]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[zaKasuPOS] ADD  CONSTRAINT [DF__zaKasuPOS__Cena__1AF3F935]  DEFAULT ((0)) FOR [Cena]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__zaKasuPOS__Tarif__1BE81D6E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[zaKasuPOS] ADD  CONSTRAINT [DF__zaKasuPOS__Tarif__1BE81D6E]  DEFAULT ('D') FOR [Tarifa]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__zaKasuPOS__Ind_d__1CDC41A7]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[zaKasuPOS] ADD  CONSTRAINT [DF__zaKasuPOS__Ind_d__1CDC41A7]  DEFAULT ('N') FOR [Ind_deckol]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__zaKasuPOS__Ind_o__1DD065E0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[zaKasuPOS] ADD  CONSTRAINT [DF__zaKasuPOS__Ind_o__1DD065E0]  DEFAULT ('N') FOR [Ind_otv]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__zaKasuPOS__Ind_b__1EC48A19]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[zaKasuPOS] ADD  CONSTRAINT [DF__zaKasuPOS__Ind_b__1EC48A19]  DEFAULT ('N') FOR [Ind_bottle]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__zaKasuPOS__Unos___1FB8AE52]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[zaKasuPOS] ADD  CONSTRAINT [DF__zaKasuPOS__Unos___1FB8AE52]  DEFAULT ('N') FOR [Unos_l]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Zakljucenja_Objekat]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF_Zakljucenja_Objekat]  DEFAULT (N'1') FOR [Objekat]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Zakljucenja_Kasa]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF_Zakljucenja_Kasa]  DEFAULT (N'1') FOR [Kasa]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Zakljucenja_Zakljucenje]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF_Zakljucenja_Zakljucenje]  DEFAULT ((0)) FOR [Zakljucenje]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Zakljucenja_Total]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF_Zakljucenja_Total]  DEFAULT ((0)) FOR [Total]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Zakljucenja_TaxA]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF_Zakljucenja_TaxA]  DEFAULT ((0)) FOR [TaxA]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Zakljucenja_TaxB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF_Zakljucenja_TaxB]  DEFAULT ((0)) FOR [TaxB]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Zakljucenja_TaxC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF_Zakljucenja_TaxC]  DEFAULT ((0)) FOR [TaxC]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Zakljucenja_TaxD]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF_Zakljucenja_TaxD]  DEFAULT ((0)) FOR [TaxD]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Zakljucenja_TaxE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF_Zakljucenja_TaxE]  DEFAULT ((0)) FOR [TaxE]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Zakljucenja_TaxF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF_Zakljucenja_TaxF]  DEFAULT ((0)) FOR [TaxF]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Zakljucenja_TaxG]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF_Zakljucenja_TaxG]  DEFAULT ((0)) FOR [TaxG]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Zakljucenja_TaxH]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF_Zakljucenja_TaxH]  DEFAULT ((0)) FOR [TaxH]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Zakljucen__BrRac__541767F8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF__Zakljucen__BrRac__541767F8]  DEFAULT ((0)) FOR [BrRacuna]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Zakljucen__BrPop__550B8C31]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF__Zakljucen__BrPop__550B8C31]  DEFAULT ((0)) FOR [BrPopusta]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Zakljucen__Popus__55FFB06A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF__Zakljucen__Popus__55FFB06A]  DEFAULT ((0)) FOR [Popusti]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Zakljucen__BrSto__56F3D4A3]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF__Zakljucen__BrSto__56F3D4A3]  DEFAULT ((0)) FOR [BrStorna]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Zakljucen__Storn__57E7F8DC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF__Zakljucen__Storn__57E7F8DC]  DEFAULT ((0)) FOR [Storna]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Zakljucen__BrArt__58DC1D15]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF__Zakljucen__BrArt__58DC1D15]  DEFAULT ((0)) FOR [BrArtikala]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Zakljucen__BrPro__59D0414E]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF__Zakljucen__BrPro__59D0414E]  DEFAULT ((0)) FOR [BrProdaja]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Zakljucen__Gotov__6FBF826D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF__Zakljucen__Gotov__6FBF826D]  DEFAULT ((0)) FOR [Gotovina]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Zakljucenja__Cek__70B3A6A6]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF__Zakljucenja__Cek__70B3A6A6]  DEFAULT ((0)) FOR [Cek]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Zakljucen__Karti__71A7CADF]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF__Zakljucen__Karti__71A7CADF]  DEFAULT ((0)) FOR [Kartice]
END

GO

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Zakljucen__Kredi__729BEF18]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Zakljucenja] ADD  CONSTRAINT [DF__Zakljucen__Kredi__729BEF18]  DEFAULT ((0)) FOR [Kredit]
END

GO


-- KRAJ TABELE
SET QUOTED_IDENTIFIER ON
GO



-- Triggers

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[trgKalkMp0UpdateKnjizeno]'))
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Dejan
-- Create date: 10.4.2010
-- Description:	Okida ažuriranje ArtikliFP kad se proknjiži kalkulacija
-- =============================================
CREATE TRIGGER [dbo].[trgKalkMp0UpdateKnjizeno] 
   ON  [dbo].[KalkMP0] 
   AFTER UPDATE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	IF UPDATE(Knjizeno)
	BEGIN
		BEGIN TRY
			DECLARE @Broj AS INT
			DECLARE @Knj AS BIT
			DECLARE @Obj AS NVARCHAR(6)
			DECLARE @RC int
			SELECT TOP 1 @Broj = i.Broj, @Knj = i.Knjizeno, @Obj = i.Objekat 
				FROM INSERTED i
			IF @Broj IS NULL
				RETURN
			IF @Knj = 0
				EXECUTE @RC = [dbo].[ArtikliFPPrepis] @Obj
			ELSE
				EXECUTE @RC = [dbo].[ArtikliFPPrepisKalkMP] @Broj
		END TRY
		BEGIN CATCH

		END CATCH

	END


END
' 
GO




/****** Object:  Trigger [dbo].[KasaFP_DeletionTrigger]    Script Date: 04/02/2010 01:07:10 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
IF	(SELECT COUNT(*) FROM [dbo].[PL_PosTerminali]) = 0
BEGIN
	INSERT [dbo].[PL_PosTerminali] ([PosTerminal], [Banka], [Partner], [Aktivan]) VALUES (1, N'CKB', N'K100', 1)
	INSERT [dbo].[PL_PosTerminali] ([PosTerminal], [Banka], [Partner], [Aktivan]) VALUES (2, N'NLB', N'K200', 1)
	--INSERT [dbo].[PL_PosTerminali] ([PosTerminal], [Banka], [Partner], [Aktivan]) VALUES (3, N'Atlasmont', N'K300', 1)
	--INSERT [dbo].[PL_PosTerminali] ([PosTerminal], [Banka], [Partner], [Aktivan]) VALUES (90, N'Interne Kartice', N'K900', 1)
END
GO


IF	(SELECT COUNT(*) FROM [dbo].[PLKartice]) > 0
	DELETE FROM [dbo].[PLKartice]
INSERT [dbo].[PLKartice] ([CardID], [PosTerminal], [Naziv], [Partner]) 
	VALUES (1, 1, N'Master', N'K101')
INSERT [dbo].[PLKartice] ([CardID], [PosTerminal], [Naziv], [Partner]) 
	VALUES (2, 1, N'Visa', N'K101')
INSERT [dbo].[PLKartice] ([CardID], [PosTerminal], [Naziv], [Partner]) 
	VALUES (3, 1, N'Diners', N'K103')
INSERT [dbo].[PLKartice] ([CardID], [PosTerminal], [Naziv], [Partner]) 
	VALUES (4, 1, N'American Express', N'K101')
INSERT [dbo].[PLKartice] ([CardID], [PosTerminal], [Naziv], [Partner]) 
	VALUES (5, 1, N'Maestro', N'K101')
INSERT [dbo].[PLKartice] ([CardID], [PosTerminal], [Naziv], [Partner]) 
	VALUES (1, 2, N'Master', N'K201')
INSERT [dbo].[PLKartice] ([CardID], [PosTerminal], [Naziv], [Partner]) 
	VALUES (2, 2, N'Visa', N'K201')
INSERT [dbo].[PLKartice] ([CardID], [PosTerminal], [Naziv], [Partner]) 
	VALUES (3, 2, N'Diners', N'K203')
INSERT [dbo].[PLKartice] ([CardID], [PosTerminal], [Naziv], [Partner]) 
	VALUES (4, 2, N'American Express', N'K201')
INSERT [dbo].[PLKartice] ([CardID], [PosTerminal], [Naziv], [Partner]) 
	VALUES (5, 2, N'Maestro', N'K201')


Insert Into Partneri (Partner, NazivFirme, Kupac) 
	SELECT DISTINCT Partner, (SELECT TOP 1 Naziv FROM dbo.PLKartice pl WHERE Partner = dbo.PLKartice.Partner) NazivFirme, 1 AS kupac 
	FROM dbo.PLKartice 
	WHERE NOT Partner IN (SELECT Partner FROM dbo.Partneri)
	
GO

-- UBACI OPERATERE
-- UBACI dva KASIRA,  JEDNOG MENADŽERA i jednog administratora
IF (SELECT COUNT(*) FROM [dbo].[Korisnici]) = 0
BEGIN
INSERT INTO [dbo].[Korisnici]
           ([RBr]
           ,[Korisnik]
           ,[Lozinka]
           ,[Ime]
           ,[ID]
           ,[Nivo]
           ,[Aktivan])
     VALUES
           (1
           ,'Kasir 1'
           ,'0000'
           ,'Kasir 1'
           ,'001'
           ,1
           ,1)
INSERT INTO [dbo].[Korisnici]
           ([RBr]
           ,[Korisnik]
           ,[Lozinka]
           ,[Ime]
           ,[ID]
           ,[Nivo]
           ,[Aktivan])
     VALUES
           (2
           ,'Kasir 2'
           ,'0000'
           ,'Kasir 2'
           ,'002'
           ,1
           ,1)
INSERT INTO [dbo].[Korisnici]
           ([RBr]
           ,[Korisnik]
           ,[Lozinka]
           ,[Ime]
           ,[ID]
           ,[Nivo]
           ,[Aktivan])
     VALUES
           (3
           ,'Kasir 3'
           ,'0000'
           ,'Kasir 3'
           ,'003'
           ,1
           ,1)
INSERT INTO [dbo].[Korisnici]
           ([RBr]
           ,[Korisnik]
           ,[Lozinka]
           ,[Ime]
           ,[ID]
           ,[Nivo]
           ,[Aktivan])
     VALUES
           (4
           ,'Kasir 4'
           ,'0000'
           ,'Kasir 4'
           ,'004'
           ,1
           ,1)
INSERT INTO [dbo].[Korisnici]
           ([RBr]
           ,[Korisnik]
           ,[Lozinka]
           ,[Ime]
           ,[ID]
           ,[Nivo]
           ,[Aktivan])
     VALUES
           (5
           ,'Kasir 5'
           ,'0000'
           ,'Kasir 5'
           ,'005'
           ,1
           ,1)
INSERT INTO [dbo].[Korisnici]
           ([RBr]
           ,[Korisnik]
           ,[Lozinka]
           ,[Ime]
           ,[ID]
           ,[Nivo]
           ,[Aktivan])
     VALUES
           (6
           ,'Kasir 6'
           ,'0000'
           ,'Kasir 6'
           ,'006'
           ,1
           ,1)
INSERT INTO [dbo].[Korisnici]
           ([RBr]
           ,[Korisnik]
           ,[Lozinka]
           ,[Ime]
           ,[ID]
           ,[Nivo]
           ,[Aktivan])
     VALUES
           (7
           ,'Kasir 7'
           ,'0000'
           ,'Kasir 7'
           ,'007'
           ,1
           ,1)
INSERT INTO [dbo].[Korisnici]
           ([RBr]
           ,[Korisnik]
           ,[Lozinka]
           ,[Ime]
           ,[ID]
           ,[Nivo]
           ,[Aktivan])
     VALUES
           (8
           ,'Kasir 8'
           ,'0000'
           ,'Kasir 8'
           ,'008'
           ,1
           ,1)

INSERT INTO [dbo].[Korisnici]
           ([RBr]
           ,[Korisnik]
           ,[Lozinka]
           ,[Ime]
           ,[ID]
           ,[Nivo]
           ,[Aktivan])
     VALUES
           (100
           ,'Poslovođa'
           ,'1111'
           ,'Poslovođa'
           ,'100'
           ,2
           ,1)
INSERT INTO [dbo].[Korisnici]
           ([RBr]
           ,[Korisnik]
           ,[Lozinka]
           ,[Ime]
           ,[ID]
           ,[Nivo]
           ,[Aktivan])
     VALUES
           (999
           ,'Admin'
           ,'9876'
           ,'Admin'
           ,'999'
           ,3
           ,1)

END

GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KasaArhB0]') AND type in (N'U'))
BEGIN
-- AKO NE POSTOJI TABELA KREIRAJ JE
	CREATE TABLE [dbo].[KasaArhB](
		[Kasa] [nvarchar](3) NOT NULL,
		[Broj] [int] NOT NULL,
		[RedBroj] [smallint] NOT NULL,
		[Sifra] [int] NULL,
		[kolicina] [money] NULL,
		[cena] [money] NULL,
		[iznos] [money] NULL,
		[rabat] [smallint] NULL,
		[TarifaA] [nvarchar](1) NULL,
		[Stopa] [tinyint] NULL,
	 CONSTRAINT [PKKasa] PRIMARY KEY CLUSTERED 
	(
		[Kasa] ASC,
		[Broj] ASC,
		[RedBroj] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]

	CREATE TABLE [dbo].[KasaArhB0](
		[Kasa] [nvarchar](3) NOT NULL,
		[Broj] [int] NOT NULL,
		[Objekat] [nvarchar](3) NULL,
		[Dokument] [nvarchar](10) NULL,
		[Datum] [datetime] NULL,
		[Iznos] [money] NULL,
		[IznosPDV] [money] NULL,
		[Placanje] [smallint] NULL,
		[Promena] [smallint] NULL,
		[Partner] [nvarchar](8) NULL,
		[Smena] [int] NULL,
		[Operater] [smallint] NULL,
		[SysDatum] [datetime] NULL,
		[Poslat] [tinyint] NULL,
		[Iznos2] [money] NULL,
		[Opis] [nvarchar](60) NULL,
		[Faktura] [nvarchar](15) NULL,
	 CONSTRAINT [PKKasa0] PRIMARY KEY CLUSTERED 
	(
		[Kasa] ASC,
		[Broj] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
-- Postavi Defaulte i relaciju
	ALTER TABLE [dbo].[KasaArhB]  WITH CHECK ADD  CONSTRAINT [FKKasa0] FOREIGN KEY([Kasa], [Broj])
	REFERENCES [dbo].[KasaArhB0] ([Kasa], [Broj])
	ON DELETE CASCADE

	ALTER TABLE [dbo].[KasaArhB] CHECK CONSTRAINT [FKKasa0]

	ALTER TABLE [dbo].[KasaArhB] ADD  CONSTRAINT [DF_KasaArhB_kolicina]  DEFAULT ((0)) FOR [kolicina]

	ALTER TABLE [dbo].[KasaArhB] ADD  CONSTRAINT [DF_KasaArhB_cena]  DEFAULT ((0)) FOR [cena]

	ALTER TABLE [dbo].[KasaArhB] ADD  CONSTRAINT [DF_KasaArhB_iznos]  DEFAULT ((0)) FOR [iznos]

	ALTER TABLE [dbo].[KasaArhB] ADD  CONSTRAINT [DF_KasaArhB_rabat]  DEFAULT ((0)) FOR [rabat]

	ALTER TABLE [dbo].[KasaArhB] ADD  CONSTRAINT [DF_KasaArhB_TarifaA]  DEFAULT (N'A') FOR [TarifaA]

	ALTER TABLE [dbo].[KasaArhB] ADD  CONSTRAINT [DF_KasaArhB_Stopa]  DEFAULT ((17)) FOR [Stopa]

	ALTER TABLE [dbo].[KasaArhB0] ADD  CONSTRAINT [DF_KasaArhB0_Iznos]  DEFAULT ((0)) FOR [Iznos]

	ALTER TABLE [dbo].[KasaArhB0] ADD  CONSTRAINT [DF_KasaArhB0_IznosPDV]  DEFAULT ((0)) FOR [IznosPDV]

	ALTER TABLE [dbo].[KasaArhB0] ADD  CONSTRAINT [DF_KasaArhB0_Iznos2]  DEFAULT ((0)) FOR [Iznos2]

END
ELSE
BEGIN
	IF NOT EXISTS(SELECT * FROM sys.columns WHERE [object_id] = object_id('dbo.KasaArhB0') AND name = 'Faktura')
		ALTER TABLE dbo.KasaArhB0 ADD Faktura NVARCHAR(15) NULL
END
-- rekapitulacija pazara
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RekDanKas__Iznos__2FDA0782]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RekDanKase] DROP CONSTRAINT [DF__RekDanKas__Iznos__2FDA0782]
END

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RekDanKas__Porez__30CE2BBB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RekDanKase] DROP CONSTRAINT [DF__RekDanKas__Porez__30CE2BBB]
END

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RekDanKas__Popus__31C24FF4]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RekDanKase] DROP CONSTRAINT [DF__RekDanKas__Popus__31C24FF4]
END

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RekDanKas__Iznos__32B6742D]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RekDanKase] DROP CONSTRAINT [DF__RekDanKas__Iznos__32B6742D]
END

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RekDanKas__Porez__33AA9866]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RekDanKase] DROP CONSTRAINT [DF__RekDanKas__Porez__33AA9866]
END

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RekDanKas__Popus__349EBC9F]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RekDanKase] DROP CONSTRAINT [DF__RekDanKas__Popus__349EBC9F]
END

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RekDanKas__Iznos__3592E0D8]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RekDanKase] DROP CONSTRAINT [DF__RekDanKas__Iznos__3592E0D8]
END

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RekDanKas__Porez__36870511]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RekDanKase] DROP CONSTRAINT [DF__RekDanKas__Porez__36870511]
END

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RekDanKas__Popus__377B294A]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RekDanKase] DROP CONSTRAINT [DF__RekDanKas__Popus__377B294A]
END

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RekDanKas__Svega__386F4D83]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RekDanKase] DROP CONSTRAINT [DF__RekDanKas__Svega__386F4D83]
END

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RekDanKas__Iznos__396371BC]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RekDanKase] DROP CONSTRAINT [DF__RekDanKas__Iznos__396371BC]
END

GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__RekDanKas__Iznos__3A5795F5]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[RekDanKase] DROP CONSTRAINT [DF__RekDanKas__Iznos__3A5795F5]
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RekDanKase]') AND type in (N'U'))
DROP TABLE [dbo].[RekDanKase]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[RekDanKase](
	[IDPaz] [int] IDENTITY(1,1) NOT NULL,
	[Datum] [datetime] NULL,
	[Objekat] [nvarchar](3) NULL,
	[Kasa] [nvarchar](3) NOT NULL,
	[Partner] [nvarchar](8) NULL,
	[Dokument] [nvarchar](10) NOT NULL,
	[Placanje] [smallint] NULL,
	[VrstaPlacanja] [nvarchar](20) NULL,
	[Kartica] [nvarchar](30) NULL,
	[IznosA] [money] NULL,
	[PorezA] [money] NULL,
	[PopustA] [money] NULL,
	[IznosB] [money] NULL,
	[PorezB] [money] NULL,
	[PopustB] [money] NULL,
	[IznosC] [money] NULL,
	[PorezC] [money] NULL,
	[PopustC] [money] NULL,
	[Svega] [money] NULL,
	[Iznos2] [money] NULL,
	[IznosTr] [money] NULL,
	[Broj] [int] NULL,
 CONSTRAINT [PK_RekDanKase] PRIMARY KEY CLUSTERED 
(
	[IDPaz] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[RekDanKase] ADD  DEFAULT ((0)) FOR [IznosA]
GO

ALTER TABLE [dbo].[RekDanKase] ADD  DEFAULT ((0)) FOR [PorezA]
GO

ALTER TABLE [dbo].[RekDanKase] ADD  DEFAULT ((0)) FOR [PopustA]
GO

ALTER TABLE [dbo].[RekDanKase] ADD  DEFAULT ((0)) FOR [IznosB]
GO

ALTER TABLE [dbo].[RekDanKase] ADD  DEFAULT ((0)) FOR [PorezB]
GO

ALTER TABLE [dbo].[RekDanKase] ADD  DEFAULT ((0)) FOR [PopustB]
GO

ALTER TABLE [dbo].[RekDanKase] ADD  DEFAULT ((0)) FOR [IznosC]
GO

ALTER TABLE [dbo].[RekDanKase] ADD  DEFAULT ((0)) FOR [PorezC]
GO

ALTER TABLE [dbo].[RekDanKase] ADD  DEFAULT ((0)) FOR [PopustC]
GO

ALTER TABLE [dbo].[RekDanKase] ADD  DEFAULT ((0)) FOR [Svega]
GO

ALTER TABLE [dbo].[RekDanKase] ADD  DEFAULT ((0)) FOR [Iznos2]
GO

ALTER TABLE [dbo].[RekDanKase] ADD  DEFAULT ((0)) FOR [IznosTr]
GO


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PopisTerm]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[PopisTerm](
		[Term] [varchar](3) NOT NULL,
		[PopisID] [int] NOT NULL,
		[Sifra] [int] NOT NULL,
		[Kolicina] [numeric](10, 3) NOT NULL,
		[Cena] [numeric](9, 2) NOT NULL,
		[Opis] [nvarchar](50) NULL,
		[Barkod] [varchar](13) NULL,
		[Datum] [smalldatetime] NULL,
		[Lista] [int] NULL,
		[Prenet] [bit] NULL,
		[DatumTerm] [smalldatetime] NULL,
		[SysDatum] [smalldatetime] NULL,
		[Objekat] [varchar](3) NULL,
		[Tabela] [varchar](15) NULL,
		[Dokument] [varchar](20) NULL,
		[Ocitavanje] [varchar](20) NULL,
		[FakCena] [numeric](10, 3) NULL,
		[Rabat] [numeric](6, 3) NULL,
		[Tarifa] [varchar](4) NULL,
		[Stopa] [numeric](5, 2) NULL,
		[Promena] [smallint] NULL,
		[Broj] [int] NULL,
	 CONSTRAINT [PK_PopisTerm] PRIMARY KEY CLUSTERED 
	(
		[Term] ASC,
		[PopisID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_Popis_Kolicina]  DEFAULT ((0)) FOR [Kolicina]
	ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_Cena]  DEFAULT ((0)) FOR [Cena]
	ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_SysDatum]  DEFAULT (CONVERT([datetime],CONVERT([varchar],getdate(),(1)),(1))) FOR [Datum]
	ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_Lista]  DEFAULT ((1)) FOR [Lista]
	ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_Prenet]  DEFAULT ((0)) FOR [Prenet]
	ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_SysDatum_1]  DEFAULT (getdate()) FOR [SysDatum]
	ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_Dokument]  DEFAULT (N'0001') FOR [Dokument]
	ALTER TABLE [dbo].[PopisTerm] ADD  CONSTRAINT [DF_PopisTerm_Promena]  DEFAULT ((125)) FOR [Promena]
END

GO

SET ANSI_PADDING OFF
GO




--

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- procedura za punjenje artikala
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliFPPrepis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ArtikliFPPrepis]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[ArtikliFPPrepis]
	@Obj as nvarchar(6) = '1'
AS
-- prvo ubaci nove artikle
insert into ArtikliFP 
	(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija, PluVaga)
select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija, a.PLU 
from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra);

-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Cena <> Round(s.CenaS,2)

-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
Update afp set afp.Zalihe = s.Zalihe
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Zalihe <> s.Zalihe
-- azuriraj nazive ako su menjani
Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.NazivArtikla <> a.NazivArtikla
-- tarife poreza
Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	inner join Tarife T on a.Tarifa = T.Tarifa
	where afp.Tarifa <> T.TarifaA


-- azuriraj barkod ili jedinicu mere
Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm, afp.PluVaga = a.Plu
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where ISNULL(afp.Barkod, '') <> ISNULL(a.Barkod, '') or ISNULL(afp.jm, '') <> ISNULL(a.jm, '')
	OR a.PLU <> afp.PluVaga

GO

-- pogled za fakture MP
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[RacuniKasa]'))
DROP VIEW [dbo].[RacuniKasa]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO




CREATE VIEW [dbo].[RacuniKasa]
AS
SELECT     dbo.KasaFPSt.Broj, dbo.KasaFPSt.RedBroj, a.Artikal, a.Barkod, a.Sifra, a.NazivArtikla, a.JM, dbo.KasaFPSt.Kolicina, dbo.KasaFPSt.Cena, 
                      dbo.KasaFPSt.Kolicina * dbo.KasaFPSt.Cena AS Iznos, dbo.KasaFPSt.Rabat, ROUND((dbo.KasaFPSt.Kolicina * dbo.KasaFPSt.Cena) * (dbo.KasaFPSt.Rabat / 100), 2) AS RabatIz, dbo.KasaFP.Dokument, dbo.KasaFP.Datum, dbo.KasaFP.Partner, 
                      dbo.Partneri.NazivFirme, dbo.Partneri.Mesto, dbo.Partneri.BrojPoste, dbo.Partneri.Ulica, dbo.Partneri.PIB, dbo.Partneri.RegBroj, dbo.KasaFP.Objekat, dbo.KasaFP.Valuta,
                       dbo.KasaFP.Opis, dbo.KasaFPSt.Stopa, dbo.KasaFP.Promena, dbo.KasaFP.Kasa, dbo.KasaFP.Zakljucenje, dbo.KasaFP.Placanje
FROM         dbo.KasaFP LEFT OUTER JOIN
                      dbo.Partneri ON dbo.KasaFP.Partner = dbo.Partneri.Partner INNER JOIN
                      dbo.ArtikliFP a RIGHT OUTER JOIN
                      dbo.KasaFPSt ON a.Sifra = dbo.KasaFpSt.Sifra ON dbo.KasaFP.Broj = dbo.KasaFPSt.Broj LEFT OUTER JOIN
                      dbo.Tarife ON a.Tarifa = dbo.Tarife.Tarifa
GO
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[pos2_PoreziPoZ]'))
DROP VIEW [dbo].[pos2_PoreziPoZ]
GO

CREATE VIEW [dbo].[pos2_PoreziPoZ]
AS
SELECT Kasa ,
        Zakljucenje ,
        CAST(TaxAosn - TaxAPor AS MONEY) TaxA,
        CAST(TaxBosn - TaxBPor AS MONEY) TaxB,
        CAST(TaxCosn - TaxCPor AS MONEY) TaxC,
        CAST(TaxDosn - TaxDPor AS MONEY) TaxD,
        CAST(TaxEosn - TaxEPor AS MONEY) TaxE,
        CAST(TaxFosn - TaxFPor  AS MONEY) TaxF,
        TaxAosn ,
        TaxBosn ,
        TaxCosn ,
        TaxDosn ,
        TaxEosn ,
        TaxFosn ,
        TaxAPor ,
        TaxBPor ,
        TaxCPor ,
        TaxDPor ,
        TaxEPor ,
        TaxFPor 
FROM
(SELECT Kasa, Zakljucenje
	, CASE WHEN TarifaA = 'A' THEN iznos 
		ELSE 0.00 END
		AS TaxAosn
	, CASE WHEN TarifaA = 'B' THEN iznos 
		ELSE 0.00 END
		AS TaxBosn
	, CASE WHEN TarifaA = 'C' THEN iznos 
		ELSE 0.00 END
		AS TaxCosn
	, CASE WHEN TarifaA = 'D' THEN iznos 
		ELSE 0.00 END
		AS TaxDosn
	, CASE WHEN TarifaA = 'E' THEN iznos 
		ELSE 0.00 END
		AS TaxEosn
	, CASE WHEN TarifaA = 'F' THEN iznos 
		ELSE 0.00 END
		AS TaxFosn
	, CASE WHEN TarifaA = 'A' THEN ROUND(iznos * stopaPrer,2)
		ELSE 0.00 END
		AS TaxAPor
	, CASE WHEN TarifaA = 'B' THEN ROUND(iznos * stopaPrer,2)
		ELSE 0.00 END
		AS TaxBPor
	, CASE WHEN TarifaA = 'C' THEN ROUND(iznos * stopaPrer,2)
		ELSE 0.00 END
		AS TaxCPor
	, CASE WHEN TarifaA = 'D' THEN ROUND(iznos * stopaPrer,2)
		ELSE 0.00 END
		AS TaxDPor
	, CASE WHEN TarifaA = 'E' THEN ROUND(iznos * stopaPrer,2)
		ELSE 0.00 END
		AS TaxEPor
	, CASE WHEN TarifaA = 'F' THEN ROUND(iznos * stopaPrer,2)
		ELSE 0.00 END
		AS TaxFPor
 FROM
(SELECT Kasa, Zakljucenje
	, TarifaA
	, st.Stopa
	, CAST(ROUND(((st.Stopa * 100) / (st.Stopa + 100)) / 100, 4) AS NUMERIC(7,4)) stopaPrer
	, SUM((st.Kolicina * st.Cena) * (1 - (cast(st.Rabat as Money) / 100))) iznos
FROM dbo.KasaFPSt st
GROUP BY st.Kasa, st.Zakljucenje, st.Stopa, st.TarifaA) por) porezi
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[pos2_Zakljucenja]'))
DROP VIEW [dbo].[pos2_Zakljucenja]
GO

CREATE VIEW [dbo].[pos2_Zakljucenja]
AS
SELECT z.Objekat ,
          z.Kasa ,
          z.Datum ,
          z.Zakljucenje ,
          z.Total ,
          z.pdv ,
          z.taxA bezpdv,
          p.TaxA,
          p.TaxB, 
          p.TaxC,
          p.TaxD,
          p.TaxE,
          p.TaxF,
--          PosSerijskiBroj ,
--          PosFM ,
          z.BrRacuna ,
          s.BrPopusta ,
          s.Popusti ,
          s.BrStorna ,
          s.Storna ,
          s.brartikala ,
          z.brracuna BrProdaja ,
          Gotovina ,
          Cek ,
          Kartice ,
          Kredit
from
(SELECT Objekat, Kasa, MAX(Datum) datum, Zakljucenje
	, SUM(Iznos) total
	, SUM(IznosPDV) pdv
	, SUM(Iznos - IznosPDV) taxA
	, COUNT(*) AS brracuna
	, SUM(Gotovina) gotovina 
	, SUM(Racun) cek 
	, SUM(Kartica) kartice 
	, SUM(Kredit) kredit 
from dbo.KasaFP
WHERE Zakljucenje > 0
GROUP BY Zakljucenje, Kasa, Objekat) z
INNER JOIN
(SELECT Kasa
	, Zakljucenje 
	, SUM(brartikala) brartikala
	, CAST(SUM(totalst) AS MONEY) totalst
	, SUM(brpopusta) brpopusta 
	, CAST(SUM(popusti) AS MONEY) popusti
	, SUM(brstorna) brstorna 
	, CAST(SUM(storna) AS MONEY) storna
FROM
(SELECT Kasa, Zakljucenje, SUM(ROUND(st.Kolicina * st.Cena,2)) totalst, COUNT(*) AS brartikala, 0.00 AS popusti, 0 AS brpopusta, 0.00 storna, 0 brstorna
	FROM dbo.KasaFPSt st
	WHERE Storno = 0
	GROUP BY Kasa, Zakljucenje
UNION ALL
SELECT Kasa, Zakljucenje, 0.00 AS totalst, 0 AS brartikala, SUM((st.Kolicina * st.Cena) * (1 - (cast(st.Rabat as Money) / 100))) AS popusti, COUNT(*) AS brpopusta, 0.00 AS storna, 0 brstorna
	FROM dbo.KasaFPSt st
	WHERE Rabat <> 0
	GROUP BY Kasa, Zakljucenje
UNION ALL
SELECT Kasa, Zakljucenje, 0.00 AS totalst, 0 AS brartikala, 0.00 AS popusti, 0 AS brpopusta, SUM((st.Kolicina * st.Cena) * (1 - (cast(st.Rabat as Money) / 100))) AS storna, COUNT(*) brstorna
	FROM dbo.KasaFPSt st
	WHERE Kolicina < 0
	GROUP BY Kasa, Zakljucenje) stavke
GROUP BY Kasa, Zakljucenje) s
ON z.Kasa = s.Kasa AND z.Zakljucenje = s.Zakljucenje
INNER JOIN dbo.pos2_PoreziPoZ p ON s.Kasa = p.Kasa AND s.Zakljucenje = p.Zakljucenje


GO


IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[pos2_Zakljucenja1]'))
DROP VIEW [dbo].[pos2_Zakljucenja1]
GO

CREATE VIEW [dbo].[pos2_Zakljucenja1]
AS
SELECT z.Objekat ,
          z.Kasa ,
          z.Datum ,
          z.Zakljucenje ,
          z.Total ,
          z.pdv ,
          z.taxA bezpdv,
          z.BrRacuna ,
          s.BrPopusta ,
          s.Popusti ,
          s.BrStorna ,
          s.Storna ,
          s.brartikala ,
          z.brracuna BrProdaja ,
          Gotovina ,
          Cek ,
          Kartice ,
          Kredit
from
(SELECT Objekat, Kasa, MAX(Datum) datum, Zakljucenje
	, SUM(Iznos) total
	, SUM(IznosPDV) pdv
	, SUM(Iznos - IznosPDV) taxA
	, COUNT(*) AS brracuna
	, SUM(Gotovina) gotovina 
	, SUM(Racun) cek 
	, SUM(Kartica) kartice 
	, SUM(Kredit) kredit 
from dbo.KasaFP
WHERE Zakljucenje > 0
GROUP BY Zakljucenje, Kasa, Objekat) z
INNER JOIN
(SELECT Kasa
	, Zakljucenje 
	, SUM(brartikala) brartikala
	, CAST(SUM(totalst) AS MONEY) totalst
	, SUM(brpopusta) brpopusta 
	, CAST(SUM(popusti) AS MONEY) popusti
	, SUM(brstorna) brstorna 
	, CAST(SUM(storna) AS MONEY) storna
FROM
(SELECT Kasa, Zakljucenje, SUM(ROUND(st.Kolicina * st.Cena,2)) totalst, COUNT(*) AS brartikala, 0.00 AS popusti, 0 AS brpopusta, 0.00 storna, 0 brstorna
	FROM dbo.KasaFPSt st
	WHERE Storno = 0
	GROUP BY Kasa, Zakljucenje
UNION ALL
SELECT Kasa, Zakljucenje, 0.00 AS totalst, 0 AS brartikala, SUM((st.Kolicina * st.Cena) * (1 - (cast(st.Rabat as Money) / 100))) AS popusti, COUNT(*) AS brpopusta, 0.00 AS storna, 0 brstorna
	FROM dbo.KasaFPSt st
	WHERE Rabat <> 0
	GROUP BY Kasa, Zakljucenje
UNION ALL
SELECT Kasa, Zakljucenje, 0.00 AS totalst, 0 AS brartikala, 0.00 AS popusti, 0 AS brpopusta, SUM((st.Kolicina * st.Cena) * (1 - (cast(st.Rabat as Money) / 100))) AS storna, COUNT(*) brstorna
	FROM dbo.KasaFPSt st
	WHERE Kolicina < 0
	GROUP BY Kasa, Zakljucenje) stavke
GROUP BY Kasa, Zakljucenje) s
ON z.Kasa = s.Kasa AND z.Zakljucenje = s.Zakljucenje



GO



-- tabela za formiranje plu-ova ako nisu uneti u tabelu Artikli
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[trgArtikliFPInsert]'))
DROP TRIGGER [dbo].[trgArtikliFPInsert]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pos2_NapraviRacun]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pos2_NapraviRacun]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[bof_PrepisPopisauBT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[bof_PrepisPopisauBT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[posB_KnjiziProdaju]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[posB_KnjiziProdaju]
GO

--pos2_ArtikliDan
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pos2_ArtikliDan]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pos2_ArtikliDan]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliFPPrepisPopis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ArtikliFPPrepisPopis]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[bof_PrepisPrijemnica]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[bof_PrepisPrijemnica]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliFPPrepisNivelMP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ArtikliFPPrepisNivelMP]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliFPPrepisKalkMP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ArtikliFPPrepisKalkMP]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliBcpPrepis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ArtikliBcpPrepis]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[IOSeSredi]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[IOSeSredi]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SelektGlKnjige]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SelektGlKnjige]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[posSlanjeArtikalaNaPos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[posSlanjeArtikalaNaPos]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[posAzurirajZalihe]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[posAzurirajZalihe]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pos2_PazarDan]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pos2_PazarDan]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pos2_PrepisZ]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pos2_PrepisZ]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pos2_PrepisZ]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pos2_PrepisZ]
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliFPPrepis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ArtikliFPPrepis]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[posAzurirajZaliheFP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[posAzurirajZaliheFP]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PopisTermSelect]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PopisTermSelect]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliZaTerminal]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ArtikliZaTerminal]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Art3xZaTerminal]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[Art3xZaTerminal]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PopisTermUpdateCmd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PopisTermUpdateCmd]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PopisaTermInsert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PopisaTermInsert]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PopisTermImportUDldPro]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PopisTermImportUDldPro]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PopisTermSelectByLista]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PopisTermSelectByLista]
GO


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Dejan Dabić>
-- ALTER  date: <ALTER  Date,, 23/4/2007>
-- Description:	<Description,, Formiranje fakture i knjizenje sa kase na osnovu prosledjenog broja Fiskalnog Bona
-- =============================================
CREATE PROCEDURE [dbo].[pos2_NapraviRacun] (@lBroj int)
AS
BEGIN
	
	SET NOCOUNT ON;
	DECLARE @MaxBroj int, @MaxProtokol int, @i int, @Iznos money
	DECLARE @Prodavnica nvarchar(3), @Part as nvarchar(8)
	DECLARE @KnjiziTK  bit
	DECLARE @MaxDok as nvarchar(7) 
	declare @lBrojDok as int
	declare @maxDokument as varchar(7)
	declare @lPref as int
	DECLARE @lBroj0 as int
	set @lBroj0 = @lBroj
	declare @Pref as nvarchar(3)
	set @Pref = ISNULL((select Prefiks from VrstePromena where Promena = 211), '')
	set @lPref = len(@Pref)
 	SET @MaxBroj = (SELECT Max(Broj) as maxProt From Izlaz0) 
 	if @MaxBroj is null 
 		set @MaxBroj = 0
 	SET @MaxBroj = @MaxBroj + 1
	set @MaxDok = (select max(dokument) as dok from Izlaz0 where left(Dokument, @lPref) = @Pref and Promena = 211)
 	if @MaxDok is null 
 		--set @MaxDok = @Pref + '0001'
		set @lBrojDok = 0
	else
		set @lBrojDok = cast(substring(@maxDok, @lPref + 1, 7 - @lPref) as int)
	set @lBrojDok = @lBrojDok + 1
	SET @MaxDok = @Pref + right('000000' + CAST(@lBrojDok as varchar(5)), 7 - @lPref)
	set @Iznos = (Select Sum(Kolicina * Cena) from dbo.KasaFPSt Where Broj = @lBroj)
	if @Iznos is Null
		begin
		Select '-1' as Dokument 
		Return -1
	END
	insert into izlaz0 (Broj, Objekat, Dokument, Datum, Valuta, Promena, Placanje, [Partner], Opis, Kasa, BrojBona, Iznos)
		select @MaxBroj as Broj, rs.Objekat, @MaxDok as Dok, convert(datetime, convert(varchar(10), rs.Datum, 102), 102) as Datum, dateadd(day, 2, rs.Datum) as Valuta, 211 as Promena, 1 as Placanje, rs.Partner, 'Na osnovu Fiskalnog bona> ' + rs.Dokument, rs.Kasa, rs.Dokument, @Iznos as Iznos
			from dbo.KasaFP rs where Broj = @lBroj
	insert into izlaz (Broj, RedBroj, Sifra, Kolicina, Cena, Iznos, Rabat, Stopa, Tarifa)
		select @MaxBroj as Broj, rs.RedBroj, rs.Sifra, rs.Kolicina, rs.Cena, ROUND(rs.Kolicina * rs.Cena, 2) AS Iznos, rs.Rabat, rs.Stopa, rs.TarifaA
			from dbo.KasaFPSt rs where Broj = @lBroj
	set @lBroj = @MaxBroj
-- ovde promenite sifru objekta za koji se prave izlazne fakture MP	
	SET @KnjiziTK  = 1
	SELECT * into #t From Izlaz0 where Broj = @lBroj
	SET @Prodavnica = (select top 1 Objekat from #t)
 	SET @MaxProtokol = (SELECT Max(Protokol) as maxProt From #t)
	if @MaxProtokol is Null 
 		set @MaxProtokol = 0
	if @MaxProtokol = 0 
	BEGIN
	 	SET @MaxProtokol = (SELECT Max(Protokol) as maxProt From Robno) 
	 	if @MaxProtokol is null 
	 		set @MaxProtokol = 0
	 	SET @MaxProtokol = @MaxProtokol + 1
	END
-- proveri da li je već knjzeno
	SET @i = (select Count(*) from dbo.Robno where Protokol = @MaxProtokol)
	IF @i >= 1 -- ako postoji knjizenje / vrati zalihe pa onda obrisi knjizenja i nastavi
	BEGIN
		PRINT 'postoji knjiženje po ovoj fakturi'
-- vrati zalihe
		create table #rs0 (Objekat nvarchar(3) not null, Sifra int not null, Izlaz money, Iznos money, Cena money, CONSTRAINT [PK_tmpRs0] PRIMARY KEY  ([Objekat], [Sifra]))
		Insert Into #rs0 (Objekat, Sifra, Izlaz, Iznos, Cena)
			select Objekat, Sifra, 
				Sum(Izlaz) as Izlaz, 
				Sum(Izlaz * ProdCena) as Iznos, 
				Max(ProdCena) as Cena  
			From RobnoStavke 
			Where Protokol = @MaxProtokol Group by Objekat, Sifra
		INSERT INTO Stanje (Objekat, Sifra, Cena, Zalihe) Select Objekat, Sifra, Cena, 0 as Zalihe From #rs0 as rs where Not Exists (Select Sifra From Stanje ss Where Sifra = rs.Sifra and Objekat = rs.Objekat)	
		UPDATE Stanje Set Zalihe = Zalihe + rs.Izlaz, Vrednost = Vrednost + rs.Iznos From #rs0 as rs where Stanje.Objekat = rs.Objekat AND Stanje.Sifra = rs.Sifra
		drop table #rs0
		delete from dbo.RobnoStavke where Protokol = @MaxProtokol
		delete from dbo.Robno where Protokol = @MaxProtokol
		delete from dbo.TrgKnjiga where Protokol = @MaxProtokol
		delete from dbo.tPromet where Protokol = @MaxProtokol
		delete from dbo.Promet where Protokol = @MaxProtokol
		delete from dbo.ira where Protokol = @MaxProtokol
		Update Izlaz set Protokol = 0, Knjizeno = 0 where  Broj = @lBroj
		Update Izlaz0 set Protokol = 0, Knjizeno = 0, Ok = 0 where  Broj = @lBroj
	END
	
	BEGIN TRAN
-- prepis
	set @Part = (Select top 1 Partner From #t as t)
	set @i = (select count(Partner) from Partneri where Partner = @Part)
	if @i = 0 BEGIN
		Insert Into Partneri (Partner, NazivFirme) Values (@Part, N'Kupac ' + @Part)
	END
	INSERT INTO [dbo].[Robno]
           ([Protokol], [Broj] ,[Dokument] ,[Datum] ,[Partner] ,[Dospece] ,[Objekat] 
			,[Promena] ,[Placanje] ,[TipkPDV] ,[TipuPDV] ,[Operater] ,[Opis])
	SELECT
           @MaxProtokol as Protokol
           ,t.Broj
           ,t.Dokument
           ,t.Datum
           ,t.Partner
           ,t.Valuta
           ,t.Objekat
           ,t.Promena
           ,t.Placanje
           ,t.TipkPDV
           ,t.TipuPDV
           ,t.Operater
           ,t.Opis
		from #t as t
	IF @@ERROR <> 0 
		BEGIN 
			RAISERROR ('Nepravilno knjiženje zaglavlja Robno.', 2, 1) 
			DELETE From Robno WHERE Protokol = @MaxProtokol 
			ROLLBACK TRANSACTION 
			RETURN -1 
		END
-- KREIRAJ ODMAH STAVKU U TK DA BI SE SPRECILO RUSENJE INTEGRITETA
	IF @KnjiziTK  <> 0 BEGIN
		INSERT INTO [dbo].[TrgKnjiga]
			(Objekat, Datum, Dokument, Pazar,  
			[Partner], Protokol, Operater)
		 SELECT
			t.Objekat, t.Datum, t.Dokument, t.Iznos,  
			t.Partner, @MaxProtokol, t.Operater
			FROM #t as t
		IF @@ERROR <> 0 
			BEGIN 
				RAISERROR ('Nepravilno kreiranje stavke u Trgovačkoj knjizi.', 3, 1) 
				DELETE From TrgKnjiga WHERE Protokol = @MaxProtokol
				ROLLBACK TRANSACTION 
				RETURN -1 
			END
	END
-- prepis stavki racuna u stavke robnog
	-- problem mogu da budu artikli koji ne postoje u bazi a postoje u prodaji artikala
declare @Novih as int
	select distinct Sifra, Tarifa into #Art from dbo.Izlaz where Izlaz.Broj = @lBroj and Not Exists (Select Sifra from Artikli Where Sifra = Izlaz.Sifra)
	set @Novih = @@ROWCOUNT
	if @Novih > 0 BEGIN
		print N'Novih art ' + cast(@Novih as nvarchar(6))
		insert into Artikli (Sifra, Artikal, Tip, Status, NazivArtikla) 
			Select a.Sifra, cast(a.Sifra as nvarchar(13)), 0 as Tip, 0 as Aktivam , N'Art ' + cast(a.Sifra as nvarchar(13)) From #Art a
	END
	DROP TABLE #Art
	INSERT INTO [dbo].[RobnoStavke] ([Protokol] ,[RedBroj], [Objekat], 
		[Sifra], [Izlaz],
		[Cena], [ProdCena], [Stopa], [Rabat], [Operater])
	SELECT @MaxProtokol as Protokol, iz.RedBroj, @Prodavnica as Objekat,  
		iz.Sifra, iz.Kolicina as Izl, 
		iz.Cena, iz.Cena as ProdCena, iz.Stopa, iz.Rabat, iz.Operater
	FROM [dbo].[Izlaz] as iz WHERE iz.Broj = @lBroj;
	IF @@ERROR <> 0 
		BEGIN 
			RAISERROR ('Nepravilno kreiranje stavki robnog.', 4, 1) 
			DELETE From RobnoStavke WHERE Protokol = @MaxProtokol
			ROLLBACK TRANSACTION 
			RETURN -1 
		END
	UPDATE Izlaz0 set Protokol = @MaxProtokol, Knjizeno = 1, Ok = 0 Where Broj = @lBroj
	UPDATE Izlaz set Protokol = @MaxProtokol, Knjizeno = 1 Where Broj = @lBroj
	UPDATE dbo.KasaFP set Protokol = @MaxProtokol, Knjizeno = 1, Faktura = @MaxDok 
		Where Broj = @lBroj
	COMMIT TRANSACTION
-- skini zalihe
	create table #rs (Objekat nvarchar(3) not null, Sifra int not null, Izlaz money, Iznos money, Cena money, CONSTRAINT [PK_tmpRs] PRIMARY KEY  ([Objekat], [Sifra]))
	Insert Into #rs (Objekat, Sifra, Izlaz, Iznos, Cena)
		select Objekat, Sifra, 
			Sum(Izlaz) as Izlaz, 
			Sum(Izlaz * ProdCena) as Iznos, 
			Max(ProdCena) as Cena  
		From RobnoStavke 
		Where Protokol = @MaxProtokol Group by Objekat, Sifra
	INSERT INTO Stanje (Objekat, Sifra, Cena, Zalihe) Select Objekat, Sifra, Cena, 0 as Zalihe From #rs as rs where Not Exists (Select Sifra From Stanje ss Where Sifra = rs.Sifra and Objekat = rs.Objekat)	
	UPDATE Stanje Set Stanje.Zalihe = Stanje.Zalihe - rs.Izlaz, Stanje.Vrednost = Stanje.Vrednost - rs.Iznos From #rs as rs where Stanje.Objekat = rs.Objekat and Stanje.Sifra = rs.Sifra
	UPDATE dbo.KasaFP set Faktura = @MaxDok, ExterniBroj = @MaxBroj, Placanje = 1 
		Where Broj = @lBroj0
	drop table #rs
	--EXEC @RC = dbo.AzurirajLager @Prodavnica, @MaxProtokol, 0, 0
Kraj:	
	drop table #t	
	Select Dokument, Datum, Iznos from Izlaz0 Where Broj = @lBroj
	RETURN 0
Greska:
	ROLLBACK TRANSACTION
	RETURN -1
END


GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


-- Prepis popisa iz Baze DLDPopis i kreiranje starih tabela BT0 i BT
CREATE PROCEDURE [dbo].[bof_PrepisPopisauBT]
AS
declare @Objekat as nvarchar(3)
declare @Dok as nvarchar(15)
declare @Br as int
set nocount on
set @Objekat = (Select top 1 Objekat from DLDPopis.dbo.Opcije)
set @Dok = (Select top 1 Dokument from DLDPopis.dbo.Popis)

if (select count(*) from Bt0 where Dokument = @Dok) > 0 begin
	print 'Postoji dokument ponisti ga pa nastavi sa prepisom'
	delete from bt where dokument = @Dok
	delete from bt0 Where Dokument = @Dok
--	Return -1
end

insert into bt0 (Dokument, Datum, Objekat)
	select distinct pop.Dokument, pop.Datum, @Objekat 
from DLDPopis.dbo.Popis pop

insert into bt (Dokument, Sifra, Barkod, Kolicina, Cena, Naziv)
	select Dokument, Sifra, Barkod, Kolicina, Cena, Opis as Naziv
from DLDPopis.dbo.Popis Order by PopisID
set @br = @@rowcount
if @br > 0 begin
	update bt set Naziv = Left(Artikli.NazivArtikla,50), Tarifa = Artikli.Tarifa 
		from Artikli Where bt.Sifra = Artikli.Sifra
	and Dokument = @Dok
	update bt set Stopa = Tarife.ZbirnaStopa 
		from Tarife Where bt.Tarifa = Tarife.Tarifa
	and Dokument = @Dok

end
-- Vrati broj insertovanih redova
return @br



GO

/****** Object:  StoredProcedure [dbo].[posB_KnjiziProdaju]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO




/****** Object:  StoredProcedure [dbo].[ArtikliFPPrepisPopis]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE procedure [dbo].[ArtikliFPPrepisPopis]
	@Broj as INT
AS

DECLARE @Obj AS NVARCHAR(6)
DECLARE @Objekat AS NVARCHAR(6)
SELECT @Obj = Objekat FROM dbo.Popis0 WHERE Broj = @Broj
IF @Obj IS NULL 
	RETURN;
SET @Objekat = @Obj
-- prvo ubaci nove artikle
insert into ArtikliFP 
	(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija, PluVaga)
select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija, a.PLU 
from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra)
	AND a.Sifra IN (SELECT Sifra FROM dbo.Popis WHERE Broj = @Broj);

-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Cena <> Round(s.CenaS,2)

-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
Update afp set afp.Zalihe = s.Zalihe
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Zalihe <> s.Zalihe
-- azuriraj nazive ako su menjani
Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.NazivArtikla <> a.NazivArtikla
-- tarife poreza
Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	inner join Tarife T on a.Tarifa = T.Tarifa
	where afp.Tarifa <> T.TarifaA


-- azuriraj barkod ili jedinicu mere
Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm, afp.PluVaga = a.Plu
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where ISNULL(afp.Barkod, '') <> ISNULL(a.Barkod, '') or ISNULL(afp.jm, '') <> ISNULL(a.jm, '')
	OR a.PLU <> afp.PluVaga
-- azuriraj slobodnu cenu ako je markiran
Update afp set afp.SlobodnaCena = a.SlobodnaCena
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Marker <> 0;

-- Mlaćenje prazne slame zbog kompatibilnosti
if exists (select * from sysobjects where id = object_id('dbo.zaKasuPOS') and sysstat & 0xf = 3)
	drop table dbo.zaKasuPOS;

CREATE TABLE dbo.zaKasuPOS (
	Objekat nvarchar (3) COLLATE Slovenian_CI_AS NOT NULL ,
	ID nvarchar (10) COLLATE Slovenian_CI_AS NOT NULL ,
	Bar_cod nvarchar (14) COLLATE Slovenian_CI_AS NULL ,
	PLU_Naziv nvarchar (25) COLLATE Slovenian_CI_AS NULL ,
	Cena money NULL CONSTRAINT DF__zaKasuPOS__Cena__1AF3F935 DEFAULT (0),
	Tarifa nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Tarif__1BE81D6E DEFAULT ('D'),
	Ind_deckol nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Ind_d__1CDC41A7 DEFAULT ('N'),
	Ind_otv nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Ind_o__1DD065E0 DEFAULT ('N'),
	Ind_bottle nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Ind_b__1EC48A19 DEFAULT ('N'),
	Kau_id nvarchar (10) COLLATE Slovenian_CI_AS NULL ,
	Unos_l nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Unos___1FB8AE52 DEFAULT ('N'),
	CONSTRAINT aaaaazaKasuPOS_PK PRIMARY KEY  NONCLUSTERED 
	(
		Objekat,
		ID
	) WITH  FILLFACTOR = 90
);
SELECT DISTINCT Sifra, Cena AS ProdCena 
INTO #Cene
FROM dbo.Popis WHERE Broj = @Broj

insert into dbo.ZaKasuPos (Objekat, [ID], Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
select @Obj as Objekat, a.Sifra, a.Barkod, 
	Left(a.NazivKasa, 24) as nn, c.ProdCena, 
	t.TarifaA , 
	'N' as Unos_l, 
	ind_deckol = case when a.Decimale = 0 THEN 'N' WHEN a.Decimale <> 0 THEN 'D' END, 
	ind_otv = case when a.SlobodnaCena = 0 THEN 'N' WHEN a.SlobodnaCena <> 0 THEN 'D' END 
From Tarife t Inner Join (Artikli a Inner Join #Cene c On a.Sifra = c.Sifra) On t.Tarifa = a.Tarifa

DROP TABLE #Cene
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'P' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena <> ArhivazaPOS.Cena
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'C' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod <> ArhivazaPOS.Bar_cod) OR (zaKasuPos.PLU_naziv <> ArhivazaPOS.PLU_naziv)  OR (zaKasuPos.Tarifa <> ArhivazaPOS.Tarifa)) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND (zaKasuPos.Bar_cod = ArhivazaPOS.Bar_cod) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod is null) and (ArhivazaPOS.Bar_cod is null)) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv)

UPDATE ArhivazaPOS Set ArhivazaPOS.Unos_l = zaKasuPos.Unos_l
	, ArhivazaPOS.Cena = zaKasuPos.Cena
	, ArhivazaPOS.Tarifa = zaKasuPos.Tarifa
	, ArhivazaPOS.Bar_cod = zaKasuPos.Bar_cod
	, ArhivazaPOS.PLU_Naziv = zaKasuPos.PLU_Naziv
	, ArhivazaPOS.ind_deckol = zaKasuPos.ind_deckol
	, ArhivazaPOS.ind_otv = zaKasuPos.ind_otv

 	from zaKasuPos 
	where ArhivazaPOS.[ID] = zaKasuPos.[ID] and ArhivazaPOS.Objekat = zaKasuPos.Objekat and zaKasuPos.Unos_l <> N'0'

Insert Into ArhivaZaPos (Objekat, [ID], Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
select Objekat, [ID], Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv from zaKasuPos
	where not exists (select Objekat, [ID] from ArhivaZaPos ar 
		where Objekat = zaKasuPos.Objekat and [ID] = zaKasuPos.[ID])

GO

/****** Object:  StoredProcedure [dbo].[bof_PrepisPrijemnica]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO




CREATE   PROCEDURE [dbo].[bof_PrepisPrijemnica]
AS
-- Zaglavlje
INSERT INTO dbo.Prijem(PrijemID, Partner, BrFakture, Iznos, Tip, Objekat, Status)
SELECT PrijemID, Dobavljac, BrFakture, Iznos, Tip, Objekat, 1 as Status 
	FROM DLDpopis.dbo.Prijem pp
	Where Not Exists (Select PrijemID From dbo.Prijem p where PrijemID = pp.PrijemID)
-- Stavke
INSERT INTO dbo.PrijemSt(PrijemID, PrijemStID, Sifra, Barkod, SKU, Kolicina, Cena, Rabat)
SELECT PrijemID, PrijemStID, Sifra, Barkod, SKU, Kolicina, Cena, Rabat 
	FROM DLDpopis.dbo.PrijemSt ps
	Where Not Exists (Select PrijemID From dbo.PrijemSt p where PrijemID = ps.PrijemID and PrijemStID = ps.PrijemStID)




GO

/****** Object:  StoredProcedure [dbo].[ArtikliFPPrepisNivelMP]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE procedure [dbo].[ArtikliFPPrepisNivelMP]
	@Broj as INT
AS

DECLARE @Obj AS NVARCHAR(6)
DECLARE @Objekat AS NVARCHAR(6)
SELECT @Obj = Objekat FROM NivelMP0 WHERE Broj = @Broj
IF @Obj IS NULL 
	RETURN;
SET @Objekat = @Obj
-- prvo ubaci nove artikle
insert into ArtikliFP 
	(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija)
select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija 
from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra)
	AND a.Sifra IN (SELECT Sifra FROM NivelMP WHERE Broj = @Broj);

-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Cena <> Round(s.CenaS,2)

-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
Update afp set afp.Zalihe = s.Zalihe
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Zalihe <> s.Zalihe
-- azuriraj nazive ako su menjani
Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.NazivArtikla <> a.NazivArtikla
-- tarife poreza
Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	inner join Tarife T on a.Tarifa = T.Tarifa
	where afp.Tarifa <> T.TarifaA


-- azuriraj barkod ili jedinicu mere
Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where ISNULL(afp.Barkod, '') <> ISNULL(a.Barkod, '') or ISNULL(afp.jm, '') <> ISNULL(a.jm, '')

-- Mlaćenje prazne slame zbog kompatibilnosti
if exists (select * from sysobjects where id = object_id('dbo.zaKasuPOS') and sysstat & 0xf = 3)
	drop table dbo.zaKasuPOS;

CREATE TABLE dbo.zaKasuPOS (
	Objekat nvarchar (3) COLLATE Slovenian_CI_AS NOT NULL ,
	ID nvarchar (10) COLLATE Slovenian_CI_AS NOT NULL ,
	Bar_cod nvarchar (14) COLLATE Slovenian_CI_AS NULL ,
	PLU_Naziv nvarchar (25) COLLATE Slovenian_CI_AS NULL ,
	Cena money NULL CONSTRAINT DF__zaKasuPOS__Cena__1AF3F935 DEFAULT (0),
	Tarifa nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Tarif__1BE81D6E DEFAULT ('D'),
	Ind_deckol nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Ind_d__1CDC41A7 DEFAULT ('N'),
	Ind_otv nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Ind_o__1DD065E0 DEFAULT ('N'),
	Ind_bottle nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Ind_b__1EC48A19 DEFAULT ('N'),
	Kau_id nvarchar (10) COLLATE Slovenian_CI_AS NULL ,
	Unos_l nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Unos___1FB8AE52 DEFAULT ('N'),
	CONSTRAINT aaaaazaKasuPOS_PK PRIMARY KEY  NONCLUSTERED 
	(
		Objekat,
		ID
	) WITH  FILLFACTOR = 90
);
SELECT DISTINCT Sifra, Cena AS ProdCena 
INTO #Cene
FROM dbo.NivelMP WHERE Broj = @Broj

insert into dbo.ZaKasuPos (Objekat, [ID], Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
select @Obj as Objekat, a.Sifra, a.Barkod, 
	Left(a.NazivKasa, 24) as nn, c.ProdCena, 
	t.TarifaA , 
	'N' as Unos_l, 
	ind_deckol = case when a.Decimale = 0 THEN 'N' WHEN a.Decimale <> 0 THEN 'D' END, 
	ind_otv = case when a.SlobodnaCena = 0 THEN 'N' WHEN a.SlobodnaCena <> 0 THEN 'D' END 
From Tarife t Inner Join (Artikli a Inner Join #Cene c On a.Sifra = c.Sifra) On t.Tarifa = a.Tarifa

DROP TABLE #Cene

UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'P' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena <> ArhivazaPOS.Cena
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'C' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod <> ArhivazaPOS.Bar_cod) OR (zaKasuPos.PLU_naziv <> ArhivazaPOS.PLU_naziv)  OR (zaKasuPos.Tarifa <> ArhivazaPOS.Tarifa)) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND (zaKasuPos.Bar_cod = ArhivazaPOS.Bar_cod) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod is null) and (ArhivazaPOS.Bar_cod is null)) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv)

UPDATE ArhivazaPOS Set ArhivazaPOS.Unos_l = zaKasuPos.Unos_l
	, ArhivazaPOS.Cena = zaKasuPos.Cena
	, ArhivazaPOS.Tarifa = zaKasuPos.Tarifa
	, ArhivazaPOS.Bar_cod = zaKasuPos.Bar_cod
	, ArhivazaPOS.PLU_Naziv = zaKasuPos.PLU_Naziv
	, ArhivazaPOS.ind_deckol = zaKasuPos.ind_deckol
	, ArhivazaPOS.ind_otv = zaKasuPos.ind_otv

 	from zaKasuPos 
	where ArhivazaPOS.[ID] = zaKasuPos.[ID] and ArhivazaPOS.Objekat = zaKasuPos.Objekat and zaKasuPos.Unos_l <> N'0'

Insert Into ArhivaZaPos (Objekat, [ID], Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
select Objekat, [ID], Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv from zaKasuPos
	where not exists (select Objekat, [ID] from ArhivaZaPos ar 
		where Objekat = zaKasuPos.Objekat and [ID] = zaKasuPos.[ID])

GO

/****** Object:  StoredProcedure [dbo].[ArtikliFPPrepisKalkMP]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE procedure [dbo].[ArtikliFPPrepisKalkMP]
	@Broj as INT
AS

DECLARE @Obj AS NVARCHAR(6)
DECLARE @Objekat AS NVARCHAR(6)
SELECT @Obj = Objekat FROM KalkMP0 WHERE Broj = @Broj
IF @Obj IS NULL 
	RETURN;
SET @Objekat = @Obj
-- prvo ubaci nove artikle
insert into ArtikliFP 
	(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija)
select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija 
from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra)
	AND a.Sifra IN (SELECT Sifra FROM KalkMP WHERE Broj = @Broj);

-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Cena <> Round(s.CenaS,2)

-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
Update afp set afp.Zalihe = s.Zalihe
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Zalihe <> s.Zalihe
-- azuriraj nazive ako su menjani
Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.NazivArtikla <> a.NazivArtikla
-- tarife poreza
Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	inner join Tarife T on a.Tarifa = T.Tarifa
	where afp.Tarifa <> T.TarifaA


-- azuriraj barkod ili jedinicu mere
Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where ISNULL(afp.Barkod, '') <> ISNULL(a.Barkod, '') or ISNULL(afp.jm, '') <> ISNULL(a.jm, '')

-- azuriraj slobodnu cenu ako je markiran
Update afp set afp.SlobodnaCena = a.SlobodnaCena
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Marker <> 0;

-- Mlaćenje prazne slame zbog kompatibilnosti
if exists (select * from sysobjects where id = object_id('dbo.zaKasuPOS') and sysstat & 0xf = 3)
	drop table dbo.zaKasuPOS;

CREATE TABLE dbo.zaKasuPOS (
	Objekat nvarchar (3) COLLATE Slovenian_CI_AS NOT NULL ,
	ID nvarchar (10) COLLATE Slovenian_CI_AS NOT NULL ,
	Bar_cod nvarchar (14) COLLATE Slovenian_CI_AS NULL ,
	PLU_Naziv nvarchar (25) COLLATE Slovenian_CI_AS NULL ,
	Cena money NULL CONSTRAINT DF__zaKasuPOS__Cena__1AF3F935 DEFAULT (0),
	Tarifa nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Tarif__1BE81D6E DEFAULT ('D'),
	Ind_deckol nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Ind_d__1CDC41A7 DEFAULT ('N'),
	Ind_otv nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Ind_o__1DD065E0 DEFAULT ('N'),
	Ind_bottle nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Ind_b__1EC48A19 DEFAULT ('N'),
	Kau_id nvarchar (10) COLLATE Slovenian_CI_AS NULL ,
	Unos_l nvarchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF__zaKasuPOS__Unos___1FB8AE52 DEFAULT ('N'),
	CONSTRAINT aaaaazaKasuPOS_PK PRIMARY KEY  NONCLUSTERED 
	(
		Objekat,
		ID
	) WITH  FILLFACTOR = 90
);
SELECT DISTINCT Sifra, PrCenaKom AS ProdCena 
INTO #Cene
FROM KalkMp WHERE Broj = @Broj

insert into dbo.ZaKasuPos (Objekat, [ID], Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
select @Obj as Objekat, a.Sifra, a.Barkod, 
	Left(a.NazivKasa, 24) as nn, c.ProdCena, 
	t.TarifaA , 
	'N' as Unos_l, 
	ind_deckol = case when a.Decimale = 0 THEN 'N' WHEN a.Decimale <> 0 THEN 'D' END, 
	ind_otv = case when a.SlobodnaCena = 0 THEN 'N' WHEN a.SlobodnaCena <> 0 THEN 'D' END 
From Tarife t Inner Join (Artikli a Inner Join #Cene c On a.Sifra = c.Sifra) On t.Tarifa = a.Tarifa

DROP TABLE #Cene

UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'P' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena <> ArhivazaPOS.Cena
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'C' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod <> ArhivazaPOS.Bar_cod) OR (zaKasuPos.PLU_naziv <> ArhivazaPOS.PLU_naziv)  OR (zaKasuPos.Tarifa <> ArhivazaPOS.Tarifa)) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND (zaKasuPos.Bar_cod = ArhivazaPOS.Bar_cod) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod is null) and (ArhivazaPOS.Bar_cod is null)) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv)

UPDATE ArhivazaPOS Set ArhivazaPOS.Unos_l = zaKasuPos.Unos_l
	, ArhivazaPOS.Cena = zaKasuPos.Cena
	, ArhivazaPOS.Tarifa = zaKasuPos.Tarifa
	, ArhivazaPOS.Bar_cod = zaKasuPos.Bar_cod
	, ArhivazaPOS.PLU_Naziv = zaKasuPos.PLU_Naziv
	, ArhivazaPOS.ind_deckol = zaKasuPos.ind_deckol
	, ArhivazaPOS.ind_otv = zaKasuPos.ind_otv

 	from zaKasuPos 
	where ArhivazaPOS.[ID] = zaKasuPos.[ID] and ArhivazaPOS.Objekat = zaKasuPos.Objekat and zaKasuPos.Unos_l <> N'0'

Insert Into ArhivaZaPos (Objekat, [ID], Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
select Objekat, [ID], Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv from zaKasuPos
	where not exists (select Objekat, [ID] from ArhivaZaPos ar 
		where Objekat = zaKasuPos.Objekat and [ID] = zaKasuPos.[ID])

GO

/****** Object:  StoredProcedure [dbo].[ArtikliBcpPrepis]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*
Procedura za preuzimanje Bcp Fajla koji se prima iz Centrale
Ovde obavezno staviti Where klauzulu kako bi se sprečio prijem nepotrebnih artikala
npr. Where NOT Grupa IN (117, 120)
*/ 

CREATE PROCEDURE [dbo].[ArtikliBcpPrepis]
AS
	SET NOCOUNT ON
	INSERT INTO dbo.Artikli
	        ( Sifra ,
	          Artikal ,
	          Tip ,
	          NazivArtikla ,
	          NazivKasa ,
	          JM ,
	          Tarifa ,
	          Grupa ,
	          Kategorija ,
	          Opis ,
	          Dobavljac ,
	          SifraKodDobavljaca ,
	          Proizvodjac ,
	          Zemlja ,
	          Cena ,
	          FakCena ,
	          VPCena ,
	          MPCena ,
	          Pakovanje ,
	          Taksa ,
	          MinZalihe ,
	          MaxZalihe ,
	          Barkod ,
	          Rabat ,
	          NabCena ,
	          Pisac ,
	          Izdavac ,
	          ISBN ,
	          RokTrajanja ,
	          Kalo ,
	          PLU ,
	          zaKasu ,
	          Grama ,
	          Decimale ,
	          SlobodnaCena ,
	          Sastav ,
	          KatBr0 ,
	          Slika ,
	          Kategorija1 ,
	          Grupa1 ,
	          Status ,
	          Tezina ,
	          NetoTezina ,
	          Zapremina ,
	          TrPak ,
	          Paleta ,
	          Carina ,
	          Dimenzije ,
	          Konto ,
	          TipVelicine ,
	          Velicina ,
	          Boja ,
	          ProizvodjacIme ,
	          Brend ,
	          ZemljaUvoza ,
	          PluFP
	        )
	Select Sifra ,
	        Artikal ,
	        Tip ,
	        NazivArtikla ,
	        NazivKasa ,
	        JM ,
	        Tarifa ,
	        Grupa ,
	        Kategorija ,
	        Opis ,
	        Dobavljac ,
	        SifraKodDobavljaca ,
	        Proizvodjac ,
	        Zemlja ,
	        Cena ,
	        FakCena ,
	        VPCena ,
	        MPCena ,
	        Pakovanje ,
	        Taksa ,
	        MinZalihe ,
	        MaxZalihe ,
	        Barkod ,
	        Rabat ,
	        NabCena ,
	        Pisac ,
	        Izdavac ,
	        ISBN ,
	        RokTrajanja ,
	        Kalo ,
	        PLU ,
	        zaKasu ,
	        Grama ,
	        Decimale ,
	        SlobodnaCena ,
	        Sastav ,
	        KatBr0 ,
	        Slika ,
	        Kategorija1 ,
	        Grupa1 ,
	        Status ,
	        Tezina ,
	        NetoTezina ,
	        Zapremina ,
	        TrPak ,
	        Paleta ,
	        Carina ,
	        Dimenzije ,
	        Konto ,
	        TipVelicine ,
	        Velicina ,
	        Boja ,
	        ProizvodjacIme ,
	        Brend ,
	        ZemljaUvoza ,
	        PluFP 
	    from ArtikliBcp b 
	    Where Not b.Sifra in (Select Sifra From Artikli)
	    AND NOT b.Grupa IN (117, 120)
	UPDATE ARTIKLI set 
		NazivArtikla =  b.NazivArtikla
		, Jm = b.Jm
		, Tarifa = b.Tarifa 
		from ArtikliBcp b 
		Where Artikli.Sifra = b.Sifra 
			and (Artikli.NazivArtikla <> b.NazivArtikla or Artikli.Jm <> b.Jm or Artikli.Tarifa <> b.Tarifa)
	UPDATE ARTIKLI set Barkod =  b.Barkod 
		from ArtikliBcp b 
		Where (Artikli.Sifra = b.Sifra) and Artikli.Barkod <> b.Barkod

GO

/****** Object:  StoredProcedure [dbo].[IOSeSredi]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create procedure [dbo].[IOSeSredi]
AS
-- Sredjivanje IOS-a
-- 1. korak, izjednaci partnere u uplatama i prometu (ako su modifikovale sifru partnera direktno u gl. knjizi)
UPDATE UPLATEKUP set Partner = Promet.Partner 
From Promet Where uplatekup.dnevnik = promet.dnevnik 
and uplatekup.partner <> promet.partner
-- 2. korak, Obrisi pogresno povezane uplate
delete from UplateKup Where not Exists (select Dnevnik from Promet where UplateKup.Dnevnik = Dnevnik) 
delete from UplateKup Where Exists (select Dnevnik, Konto, Partner from Promet where UplateKup.Dnevnik = Dnevnik and (UplateKup.Konto <> Konto Or UplateKup.Partner <> Partner)) 
delete from UplateKup Where Exists (select promet.dnevnik, promet.potrazuje, sum(uk.iznos) as uplate 
from promet inner join uplatekup uk on promet.dnevnik = uk.dnevnik 
where UplateKup.Dnevnik = Promet.dnevnik
group by promet.dnevnik, promet.potrazuje 
having promet.potrazuje <> sum(uk.iznos))
-- brisanje sirocica iz uplatedob
delete from UplateDob Where Exists (select Dnevnik, Konto, Partner from Promet where UplateDob.Dnevnik = Dnevnik and (UplateDob.Konto <> Konto Or UplateDob.Partner <> Partner)) 
delete from UplateDob Where not Exists (select Dnevnik from Promet where UplateDob.Dnevnik = Dnevnik) 
delete from UplateDob Where Exists (select promet.dnevnik, promet.duguje, sum(uk.iznos) as uplate 
from promet inner join uplatedob uk on promet.dnevnik = uk.dnevnik 
where UplateDob.Dnevnik = Promet.dnevnik
group by promet.dnevnik, promet.duguje 
having promet.duguje <> sum(uk.iznos))
-- 3. korak, pusti kontrola i ažuriranje uplata u ios-u

GO

/****** Object:  StoredProcedure [dbo].[SelektGlKnjige]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[SelektGlKnjige]
AS SELECT     dbo.Promet.Nalog, dbo.Promet.Datum, dbo.Promet.Konto, Kp.Opis AS NazivKonta, dbo.Promet.Partner, dbo.Promet.Duguje, dbo.Promet.Potrazuje, 
                      dbo.Promet.Dokument
INTO            dbo.GK2004
FROM         dbo.Promet INNER JOIN
                      dbo.KontniPlan Kp ON dbo.Promet.Konto = Kp.Konto
ORDER BY dbo.Promet.Nalog, dbo.Promet.RedBroj

GO

/****** Object:  StoredProcedure [dbo].[posSlanjeArtikalaNaPos]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[posSlanjeArtikalaNaPos]
	(@Objekat varchar(6) = '50', 
	@OdDatuma datetime = '2000-01-01',
	@DoDatuma datetime = '2049-01-01')
as
SET NOCOUNT ON;
--za novu verziju slanje artikala ide preko procedure ArtikliFPPrepis
DECLARE @RC int
DECLARE @Obj nvarchar(6)

SET @Obj = @Objekat

EXECUTE @RC = [dbo].[ArtikliFPPrepis] 
   @Obj

RETURN @RC
GO

/****** Object:  StoredProcedure [dbo].[posAzurirajZalihe]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


-- Procedura posAzurirajZalihe prepisuje lager listu iz Bof baze u bazu KasaSql
-- OVO SE RADI SAMO AKO JE BAZA BOF-A I KASE NA ISTOM SERVERU
create procedure [dbo].[posAzurirajZalihe]
as
update KasaSql.dbo.Artikli set Zalihe = st.Zalihe 
	from dbo.posStanjeZaliha st
	where KasaSql.dbo.Artikli.Sifra = st.Sifra 
	and KasaSql.dbo.Artikli.Zalihe <> st.Zalihe


GO

/****** Object:  StoredProcedure [dbo].[pos2_PazarDan]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO







-- priprema pazara za dan
CREATE PROCEDURE [dbo].[pos2_PazarDan]
(
	@Datum datetime
)
AS
	SET NOCOUNT ON;
if exists (select * from sysobjects where id = object_id('dbo.RekDanKase') and sysstat & 0xf = 3)
	drop table dbo.RekDanKase;
CREATE TABLE dbo.RekDanKase (
	IDPaz int IDENTITY(1,1) NOT NULL, 
	Datum datetime NULL ,
	Objekat nvarchar (3) NULL ,
	Kasa nvarchar (3) NOT NULL ,
	Partner nvarchar (8) NULL ,
	Dokument nvarchar (10) NOT NULL , 
	Placanje smallint NULL ,
	VrstaPlacanja nvarchar (20) NULL ,
	Kartica nvarchar (30) NULL ,
	IznosA money NULL default(0) ,
	PorezA money NULL default(0) ,
	PopustA money NULL default(0) ,
	IznosB money NULL default(0) ,
	PorezB money NULL default(0) ,
	PopustB money NULL default(0) ,
	IznosC money NULL default(0) ,
	PorezC money NULL default(0) ,
	PopustC money NULL default(0) ,
	Svega money NULL default(0) , 
	Iznos2 money null default(0) , 
	IznosTr money null default(0) , 
	Broj int null, 
CONSTRAINT PK_RekDanKase primary key (IDPaz)
) ;
CREATE TABLE #RekDanTmp (
	IDPaz0 int IDENTITY(1,1) NOT NULL, 
	Datum datetime NULL ,
	Objekat nvarchar (3) NULL ,
	Kasa nvarchar (3) NOT NULL ,
	Partner nvarchar (8) NULL ,
	Dokument nvarchar (10) NOT NULL , 
	Placanje smallint NULL ,
	VrstaPlacanja nvarchar (20) NULL ,
	Kartica nvarchar (30) NULL ,
	IznosA money NULL default(0) ,
	PorezA money NULL default(0) ,
	PopustA money NULL default(0) ,
	IznosB money NULL default(0) ,
	PorezB money NULL default(0) ,
	PopustB money NULL default(0) ,
	IznosC money NULL default(0) ,
	PorezC money NULL default(0) ,
	PopustC money NULL default(0) ,
	Svega money NULL default(0) , 
	Iznos2 money null default(0) , 
	IznosTr money null default(0) , 
	Broj int null, 
CONSTRAINT PK_RekTmp primary key (IDPaz0)
)


declare @strDat0 as nvarchar(10)
declare @strDat1 as nvarchar(10)
declare @Dat0 as datetime
declare @Dat1 as datetime

set @strDat0 = convert(nvarchar(10), @Datum, 126)
set @strDat1 = convert(nvarchar(10), DateAdd(d, 1, @Datum), 126)
set @Dat0 = convert(datetime, @strDat0 + ' 04:59:59', 102)
set @Dat1 = convert(datetime, @strDat1 + ' 05:00:00', 102)

-- PRVO GOTOVINA ZBIRNO
INSERT INTO #RekDanTmp (Datum, Objekat, Kasa, Partner, Placanje, VrstaPlacanja, Kartica, IznosA, IznosB, IznosC, PorezA, PorezB, PorezC, PopustA, PopustB, PopustC, Svega, Dokument)
SELECT     @Datum AS Datum, k.Objekat, k.Kasa, k.Partner, k.Placanje, 
			N'Gotovina' as VrstaPlacanja, Null AS Kartica, 
                      CASE WHEN st.TarifaA = N'A' THEN SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS IznosA, 
                      CASE WHEN st.TarifaA = N'B' THEN SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS IznosB,
                      CASE WHEN not st.TarifaA in('A','B') THEN SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS IznosC,
                      cast(0 as money) AS PorezA,
                      cast(0 as money) AS PorezB,
                      cast(0 as money) AS PorezC,
                      CASE WHEN st.TarifaA = N'A' THEN SUM(Round(st.Kolicina * st.Cena,2) * ((cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS PopustA, 
                      CASE WHEN st.TarifaA = N'B' THEN SUM(Round(st.Kolicina * st.Cena,2) * ((cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS PopustB,
                      CASE WHEN not st.TarifaA in('A','B') THEN SUM(Round(st.Kolicina * st.Cena,2) * ((cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS PopustC,
		SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) as Svega, N'0000' as Dokumet
FROM         dbo.KasaFPSt st INNER JOIN
                      dbo.KasaFP k ON st.Broj = k.Broj
WHERE k.ZakljucenDan <> 0 AND k.Stornirano = 0 AND k.Stornirano = 0 AND  k.Placanje = 2 and (k.Datum between @Dat0 and @Dat1)
GROUP BY k.Objekat, k.Kasa, k.Partner, k.Placanje,  k.ZakljucenDan, st.TarifaA;
-- dbo.DateValue(k.Datum)
-- samo saberi totale bonova
-- dopis gotovinske doplate u posebnu kolonu
INSERT INTO #RekDanTmp (Datum, Objekat, Kasa, Partner, Placanje, VrstaPlacanja, Kartica, Iznos2, IznosTr, Dokument)
SELECT     @Datum AS Datum, k.Objekat, k.Kasa, k.Partner, k.Placanje, 
			N'Gotovina' as VrstaPlacanja, Null AS Kartica, 
		SUM(k.Iznos2) as Iznos2, SUM(k.Iznos) as IznosTr, N'0000' as Dokumet
FROM         dbo.KasaFP k 
WHERE k.ZakljucenDan <> 0 AND k.Stornirano = 0 AND k.Stornirano = 0 AND k.Placanje = 2 and (k.Datum between @Dat0 and @Dat1)
GROUP BY  k.Objekat, k.Kasa, k.Partner, k.Placanje, k.ZakljucenDan;

-- PA KARTICE GRUPISANO PO VRSTI KARTICE
INSERT INTO #RekDanTmp (Datum, Objekat, Kasa, Partner, Placanje, VrstaPlacanja, Kartica, IznosA, IznosB, IznosC, PorezA, PorezB, PorezC, PopustA, PopustB, PopustC, Svega, Dokument)
SELECT     @Datum AS Datum, k.Objekat, k.Kasa, k.Partner, k.Placanje, 
			p.VrstaPlacanja, pk.Naziv AS Kartica, 
                      CASE WHEN st.TarifaA = N'A' THEN SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS IznosA, 
                      CASE WHEN st.TarifaA = N'B' THEN SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS IznosB,
                      CASE WHEN not st.TarifaA in('A','B') THEN SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS IznosC,
                      cast(0 as money) AS PorezA,
                      cast(0 as money) AS PorezB,
                      cast(0 as money) AS PorezC,
                      CASE WHEN st.TarifaA = N'A' THEN SUM(Round(st.Kolicina * st.Cena,2) * ((cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS PopustA, 
                      CASE WHEN st.TarifaA = N'B' THEN SUM(Round(st.Kolicina * st.Cena,2) * ((cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS PopustB,
                      CASE WHEN not st.TarifaA in('A','B') THEN SUM(Round(st.Kolicina * st.Cena,2) * ((cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS PopustC,
		SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) as Svega, N'0000' as Dokumet
FROM         dbo.KasaFPSt st INNER JOIN
                      dbo.KasaFP k ON st.Broj = k.Broj LEFT OUTER JOIN
                      dbo.Placanje p ON k.Placanje = p.Placanje LEFT OUTER JOIN
                      dbo.PLKartice pk ON k.PosTerminal = pk.PosTerminal AND k.CardID = pk.CardID -- k.Partner = dbo.PLKartice.Partner
WHERE k.ZakljucenDan <> 0 AND k.Stornirano = 0 AND k.Placanje = 3 and (k.Datum between @Dat0 and @Dat1)
GROUP BY k.Objekat, k.Kasa, k.Partner, k.Placanje, p.VrstaPlacanja, pk.Naziv, k.ZakljucenDan,
                      st.TarifaA;
-- dopis gotovinske doplate u posebnu kolonu
INSERT INTO #RekDanTmp (Datum, Objekat, Kasa, Partner, Placanje, VrstaPlacanja, Kartica, Iznos2, IznosTr, Dokument)
SELECT     @Datum as Datum, k.Objekat, k.Kasa, k.Partner, k.Placanje, 
			dbo.Placanje.VrstaPlacanja, pk.Naziv AS Kartica, 
		SUM(k.Iznos2) as Iznos2, SUM(k.Iznos) as IznosTr, N'0000' as Dokumet
FROM         dbo.KasaFP k LEFT OUTER JOIN
                      dbo.Placanje ON k.Placanje = dbo.Placanje.Placanje LEFT OUTER JOIN
                      dbo.PLKartice pk ON k.PosTerminal = pk.PosTerminal AND k.CardID = pk.CardID -- k.Partner = dbo.PLKartice.Partner
WHERE k.ZakljucenDan <> 0 AND k.Stornirano = 0 
	AND k.Placanje = 3 
	and (k.Datum between @Dat0 and @Dat1)
	AND k.Iznos2 <> 0
GROUP BY  k.Objekat, k.Kasa, k.Partner, k.Placanje, dbo.Placanje.VrstaPlacanja, pk.Naziv, k.ZakljucenDan;

-- kredit zbirno
INSERT INTO #RekDanTmp (Datum, Objekat, Kasa, Partner, Placanje, VrstaPlacanja, Kartica, IznosA, IznosB, IznosC, PorezA, PorezB, PorezC, PopustA, PopustB, PopustC, Svega, Dokument)
SELECT     @Datum as Datum, k.Objekat, k.Kasa, k.Partner, k.Placanje, 
			N'Kredit' as VrstaPlacanja, Null AS Kartica, 
                      CASE WHEN st.TarifaA = N'A' THEN SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS IznosA, 
                      CASE WHEN st.TarifaA = N'B' THEN SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS IznosB,
                      CASE WHEN not st.TarifaA in('A','B') THEN SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS IznosC,
                      cast(0 as money) AS PorezA,
                      cast(0 as money) AS PorezB,
                      cast(0 as money) AS PorezC,
                      CASE WHEN st.TarifaA = N'A' THEN SUM(Round(st.Kolicina * st.Cena,2) * ((cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS PopustA, 
                      CASE WHEN st.TarifaA = N'B' THEN SUM(Round(st.Kolicina * st.Cena,2) * ((cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS PopustB,
                      CASE WHEN not st.TarifaA in('A','B') THEN SUM(Round(st.Kolicina * st.Cena,2) * ((cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS PopustC,
		SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) as Svega, N'0000' as Dokumet
FROM         dbo.KasaFPSt st INNER JOIN
                      dbo.KasaFP k ON st.Broj = k.Broj
WHERE k.ZakljucenDan <> 0 AND k.Stornirano = 0 
	AND k.Placanje = 4 
	and (k.Datum between  @Dat0 and @Dat1)
GROUP BY  k.Objekat, k.Kasa, k.Partner, k.Placanje, k.ZakljucenDan, 
                      st.TarifaA;
-- dopis gotovinske doplate u posebnu kolonu
INSERT INTO #RekDanTmp (Datum, Objekat, Kasa, Partner, Placanje, VrstaPlacanja, Kartica, Iznos2, IznosTr, Dokument)
SELECT     @Datum as Datum, k.Objekat, k.Kasa, k.Partner, k.Placanje, 
			'Kredit' as VrstaPlacanja, Null AS Kartica, 
		SUM(k.Iznos2) as Iznos2, SUM(k.Iznos) as IznosTr, N'0000' as Dokumet
FROM         dbo.KasaFP k 
WHERE k.ZakljucenDan <> 0 AND k.Stornirano = 0 
	AND k.Placanje = 4 
	and (k.Datum between @Dat0 and @Dat1)
	AND k.Iznos2 <> 0
GROUP BY  k.Objekat, k.Kasa, k.Partner, k.Placanje, k.ZakljucenDan;

-- i na kraju SVAKA FAKTURA ZA KUPCE POJEDINACNO
INSERT INTO #RekDanTmp (Datum, Objekat, Kasa, Partner, Dokument, Placanje, VrstaPlacanja, Kartica, IznosA, IznosB, IznosC, PorezA, PorezB, PorezC, PopustA, PopustB, PopustC, Svega, Broj)
SELECT     @Datum as Datum, k.Objekat, k.Kasa, k.Partner, ISNULL(k.Faktura, k.Dokument), k.Placanje, 
			dbo.Placanje.VrstaPlacanja, Null AS Kartica, 
                      CASE WHEN st.TarifaA = N'A' THEN SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS IznosA, 
                      CASE WHEN st.TarifaA = N'B' THEN SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS IznosB,
                      CASE WHEN not st.TarifaA in('A','B') THEN SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS IznosC,
                      cast(0 as money) AS PorezA,
                      cast(0 as money) AS PorezB,
                      cast(0 as money) AS PorezC,
                      CASE WHEN st.TarifaA = N'A' THEN SUM(Round(st.Kolicina * st.Cena,2) * ((cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS PopustA, 
                      CASE WHEN st.TarifaA = N'B' THEN SUM(Round(st.Kolicina * st.Cena,2) * ((cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS PopustB,
                      CASE WHEN not st.TarifaA in('A','B') THEN SUM(Round(st.Kolicina * st.Cena,2) * ((cast(st.Rabat as Money) / 100))) ELSE cast(0 as money) END AS PopustC,
		SUM(Round(st.Kolicina * st.Cena,2) * (1 - (cast(st.Rabat as Money) / 100))) as Svega, k.Broj
FROM         dbo.KasaFPSt st INNER JOIN
                      dbo.KasaFP k ON st.Broj = k.Broj LEFT OUTER JOIN
                      dbo.Placanje ON k.Placanje = dbo.Placanje.Placanje 
WHERE k.ZakljucenDan <> 0 AND k.Stornirano = 0 AND k.Placanje = 1 and (k.Datum between @Dat0 and @Dat1)
GROUP BY  k.Objekat, k.Kasa, 
	k.Partner, k.Dokument, k.Faktura,
	k.Placanje, dbo.Placanje.VrstaPlacanja, 
        st.TarifaA, k.Broj, k.ZakljucenDan;
-- gotovinska doplata za kupce NE SME DA POSTOJI ali ako postoji stavi je u posebnu kolonu
-- dopis gotovinske doplate u posebnu kolonu
INSERT INTO #RekDanTmp (Datum, Objekat, Kasa, Partner, Dokument, Placanje, VrstaPlacanja, Kartica, Iznos2, IznosTr, Broj)
SELECT     @Datum as Datum, k.Objekat, k.Kasa, k.Partner, k.Dokument, k.Placanje, 
			dbo.Placanje.VrstaPlacanja, Null AS Kartica, 
		SUM(k.Iznos2) as Iznos2, SUM(k.Iznos) as IznosTr, k.Broj
FROM         dbo.KasaFP k LEFT OUTER JOIN
                      dbo.Placanje ON k.Placanje = dbo.Placanje.Placanje 
WHERE k.ZakljucenDan <> 0 AND k.Stornirano = 0 
	AND k.Placanje = 1 
	and (k.Datum between @Dat0 and @Dat1)
	AND k.Iznos2 <> 0
GROUP BY  k.Objekat, k.Kasa, 
	k.Partner, k.Dokument, 
	k.Placanje, dbo.Placanje.VrstaPlacanja, 
	k.Broj, k.ZakljucenDan;


Insert into  dbo.RekDanKase (Datum, Objekat, Kasa, Partner, Dokument, Placanje, VrstaPlacanja, Kartica, IznosA, IznosB, IznosC, PorezA, PorezB, PorezC, PopustA, PopustB, PopustC, Svega, Broj, Iznos2, IznosTr)
SELECT Datum, Objekat, Kasa, Partner, Dokument, Placanje, VrstaPlacanja, Kartica, Sum(IznosA) as IznosA, Sum(IznosB) as IznosB, Sum(IznosC) as IznosC, Sum(PorezA) as PorezA, Sum(PorezB) as PorezB, Sum(PorezC) as PorezC, Sum(PopustA) as PopustA, Sum(PopustB) as PopustB, Sum(PopustC) as PopustC, Sum(Svega) as Svega, Broj, Sum(Iznos2) as Iznos2, Sum(IznosTr) as IznosTr
FROM #RekDanTmp
group by Datum, Objekat, Kasa, Partner, Dokument, Placanje, VrstaPlacanja, Kartica, Broj
ORDER BY KASA, PLACANJE, DOKUMENT;

drop table #RekDanTmp
--  azuriraj sad poreze
declare @StopaA as money, @StopaB as money, @StopaC as money
set @StopaA = (select Republicki from Tarife Where TarifaA = N'A')
set @StopaB = (select Republicki from Tarife Where TarifaA = N'B')
set @StopaC = (select Republicki from Tarife Where TarifaA = N'C')
set @StopaA = isnull((@StopaA * 100) / (@StopaA + 100), 0)
set @StopaB = isnull((@StopaB * 100) / (@StopaB + 100), 0)
set @StopaC = isnull((@StopaC * 100) / (@StopaC + 100), 0)

set @StopaA = isnull(@StopaA / 100, 0)
set @StopaB = isnull(@StopaB / 100, 0)
set @StopaC = isnull(@StopaC / 100, 0)


update dbo.RekDanKase set PorezA = Round(IznosA * @StopaA,2), PorezB = Round(IznosB * @StopaB,2), PorezC = Round(IznosC * @StopaC,2)

GO

/****** Object:  StoredProcedure [dbo].[pos2_PrepisZ]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[pos2_PrepisZ]
	@kasa AS VARCHAR(3) = '101',
	@z AS SMALLINT
AS

IF (SELECT COUNT(*) br 
	FROM dbo.Zakljucenja WHERE 
	dbo.Zakljucenja.Zakljucenje = @z 
			AND dbo.Zakljucenja.Kasa = @kasa) > 0
	BEGIN
		RAISERROR ('Zaključenje Već postoji u bazi.', 2, 1) 
		RETURN -1;
	END

INSERT INTO dbo.Zakljucenja
        ( Objekat ,
          Kasa ,
          Datum ,
          Zakljucenje ,
          Total ,
          TaxA ,
--          PosSerijskiBroj ,
--          PosFM ,
          BrRacuna ,
          BrPopusta ,
          Popusti ,
          BrStorna ,
          Storna ,
          BrArtikala ,
          BrProdaja ,
          Gotovina ,
          Cek ,
          Kartice ,
          Kredit
        )
SELECT z.Objekat ,
          z.Kasa ,
          z.Datum ,
          z.Zakljucenje ,
          z.Total ,
          z.TaxA ,
--          PosSerijskiBroj ,
--          PosFM ,
          z.BrRacuna ,
          s.BrPopusta ,
          s.Popusti ,
          s.BrStorna ,
          s.Storna ,
          s.brartikala ,
          z.brracuna BrProdaja ,
          Gotovina ,
          Cek ,
          Kartice ,
          Kredit
from
(SELECT Objekat, Kasa, MAX(Datum) datum, Zakljucenje
	, SUM(Iznos) total
	, SUM(IznosPDV) pdv
	, SUM(Iznos - IznosPDV) taxA
	, COUNT(*) AS brracuna
	, SUM(Gotovina) gotovina 
	, SUM(Racun) cek 
	, SUM(Kartica) kartice 
	, SUM(Kredit) kredit 
from dbo.KasaFP
WHERE Zakljucenje = @z
GROUP BY Zakljucenje, Kasa, Objekat) z
INNER JOIN
(SELECT Kasa
	, Zakljucenje 
	, SUM(brartikala) brartikala
	, CAST(SUM(totalst) AS MONEY) totalst
	, SUM(brpopusta) brpopusta 
	, CAST(SUM(popusti) AS MONEY) popusti
	, SUM(brstorna) brstorna 
	, CAST(SUM(storna) AS MONEY) storna
FROM
(SELECT Kasa, Zakljucenje, SUM(ROUND(st.Kolicina * st.Cena,2)) totalst, COUNT(*) AS brartikala, 0.00 AS popusti, 0 AS brpopusta, 0.00 storna, 0 brstorna
	FROM dbo.KasaFPSt st
	WHERE Storno = 0 AND Zakljucenje = @z
	GROUP BY Kasa, Zakljucenje
UNION ALL
SELECT Kasa, Zakljucenje, 0.00 AS totalst, 0 AS brartikala, SUM((st.Kolicina * st.Cena) * (1 - (cast(st.Rabat as Money) / 100))) AS popusti, COUNT(*) AS brpopusta, 0.00 AS storna, 0 brstorna
	FROM dbo.KasaFPSt st
	WHERE Rabat <> 0 AND Zakljucenje = @z
	GROUP BY Kasa, Zakljucenje
UNION ALL
SELECT Kasa, Zakljucenje, 0.00 AS totalst, 0 AS brartikala, 0.00 AS popusti, 0 AS brpopusta, SUM((st.Kolicina * st.Cena) * (1 - (cast(st.Rabat as Money) / 100))) AS storna, COUNT(*) brstorna
	FROM dbo.KasaFPSt st
	WHERE Kolicina < 0 AND Zakljucenje = @z
	GROUP BY Kasa, Zakljucenje) stavke
GROUP BY Kasa, Zakljucenje) s
ON z.Kasa = s.Kasa AND z.Zakljucenje = s.Zakljucenje
WHERE z.Kasa = @kasa AND z.Zakljucenje = @z
-- porezi
DECLARE @taxA MONEY
DECLARE @taxApor MONEY
SET @taxA = (SELECT TaxA FROM dbo.Zakljucenja WHERE Kasa = @kasa AND Zakljucenje = @z)
SET @taxA = ISNULL(@taxA,0)
SET @taxApor = (SELECT TaxA FROM dbo.pos2_PoreziPoZ WHERE Kasa = @kasa AND Zakljucenje = @z)
SET @taxApor = ISNULL(@taxApor,0)

IF @taxA <> @taxApor
BEGIN
	UPDATE dbo.Zakljucenja 
	SET TaxA = pz.TaxA 
		, TaxB = pz.TaxB
		, TaxC = pz.TaxC
		, TaxD = pz.TaxD
		, TaxE = pz.TaxE
		, TaxF = pz.TaxF
		FROM dbo.pos2_PoreziPoZ pz
		WHERE dbo.Zakljucenja.Zakljucenje = @z 
			AND dbo.Zakljucenja.Kasa = @kasa
			AND dbo.Zakljucenja.Kasa = pz.Kasa
			AND dbo.Zakljucenja.Zakljucenje = pz.Zakljucenje
END

GO

/****** Object:  StoredProcedure [dbo].[ArtikliFPPrepis]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE procedure [dbo].[ArtikliFPPrepis]
	@Obj as nvarchar(6) = '1'
AS
-- prvo ubaci nove artikle
insert into ArtikliFP 
	(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija)
select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija 
from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra);

-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Cena <> Round(s.CenaS,2)

-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
Update afp set afp.Zalihe = s.Zalihe
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Zalihe <> s.Zalihe
-- azuriraj nazive ako su menjani
Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.NazivArtikla <> a.NazivArtikla
-- tarife poreza
Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	inner join Tarife T on a.Tarifa = T.Tarifa
	where afp.Tarifa <> T.TarifaA

insert into ArtikliFP 
	(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija, SlobodnaCena, Marker)
select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, 0.00 Cena, a.Barkod, 0.00 Zalihe, a.Kategorija, 1 AS SlobodnaCena, 0 AS Marker 
from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra);

-- azuriraj slobodnu cenu ako je markiran
Update afp set afp.SlobodnaCena = a.SlobodnaCena
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Marker <> 0 AND afp.Cena <> 0;

-- azuriraj barkod ili jedinicu mere
Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where ISNULL(afp.Barkod, '') <> ISNULL(a.Barkod, '') or ISNULL(afp.jm, '') <> ISNULL(a.jm, '')


GO

/****** Object:  StoredProcedure [dbo].[posAzurirajZaliheFP]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


-- Procedura posAzurirajZalihe prepisuje lager listu iz Stanja u ArtikliFP
-- OVO SE RADI SAMO AKO JE BAZA BOF-A I KASE NA ISTOM SERVERU
CREATE procedure [dbo].[posAzurirajZaliheFP]
as
DECLARE @Obj AS NVARCHAR(3)
SET @Obj = (SELECT TOP 1 Objekat FROM dbo.ArhivaZaPos)
IF @Obj IS NULL 
	RETURN;
update dbo.ArtikliFP set Zalihe = st.Zalihe 
	from (SELECT Sifra, Cena, Zalihe FROM Stanje WHERE Objekat = @Obj) st
	where dbo.ArtikliFP.Sifra = st.Sifra 
	and dbo.ArtikliFP.Zalihe <> st.Zalihe


GO

/****** Object:  StoredProcedure [dbo].[PopisTermSelect]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[PopisTermSelect]
AS
SELECT     Term, PopisID, Sifra, Kolicina, Cena, Opis, Barkod, Datum, Lista, Prenet, DatumTerm, SysDatum, Objekat, Tabela, Dokument, Ocitavanje, FakCena, Rabat, Tarifa, 
                      Stopa, Promena, Broj
FROM         PopisTerm
GO

/****** Object:  StoredProcedure [dbo].[ArtikliZaTerminal]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[ArtikliZaTerminal]
    (
      @Objekat VARCHAR(3) = '1'
	
    )
AS /* SET NOCOUNT ON */
    SELECT  a.Sifra ,
            a.Barkod ,
            LEFT(ISNULL(a.NazivArtikla, ''), 50) AS Naziv ,
            a.Jm ,
            ISNULL(s.Cena, a.Cena) AS Cena ,
            a.Kategorija ,
            a.Grupa ,
            a.SifraKodDobavljaca AS SKU ,
            ISNULL(s.Zalihe, 0) AS Zalihe
    FROM    Artikli a
            LEFT JOIN ( SELECT  Sifra ,
                                Cena ,
                                Zalihe
                        FROM    Stanje
                        WHERE   Objekat = @Objekat
                      ) s ON a.Sifra = s.Sifra	
            WHERE a.Status <> 0
    RETURN

GO

/****** Object:  StoredProcedure [dbo].[Art3xZaTerminal]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[Art3xZaTerminal]
AS
Select DISTINCT Left(Bar_Code,13) as Barkod, CAST([ID] AS INT) AS Sifra From dbo.Art3x A3 
	Where Not Bar_Code is Null
	AND NOT EXISTS (select Rtrim(Bar_code) Bk, Count(*) as br  from Art3x aa
			Where a3.Bar_code = aa.Bar_code Group by Rtrim(Bar_code) Having COunt(*) > 1)
RETURN
GO

/****** Object:  StoredProcedure [dbo].[PopisTermUpdateCmd]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[PopisTermUpdateCmd]
(
	@Term varchar(3),
	@PopisID int,
	@Sifra int,
	@Kolicina numeric(10, 3),
	@Cena numeric(9, 2),
	@Opis nvarchar(50),
	@Barkod varchar(13),
	@Datum smalldatetime,
	@Lista int,
	@Prenet bit,
	@DatumTerm smalldatetime,
	@Objekat varchar(3),
	@Tabela varchar(15),
	@Dokument varchar(20),
	@Ocitavanje varchar(20),
	@FakCena numeric(10, 3),
	@Rabat numeric(6, 3),
	@Tarifa varchar(4),
	@Stopa numeric(5, 2),
	@Promena smallint,
	@Broj int,
	@Original_Term varchar(3),
	@Original_PopisID int
)
AS
	SET NOCOUNT OFF;
UPDATE [PopisTerm] SET [Term] = @Term, [PopisID] = @PopisID, [Sifra] = @Sifra, [Kolicina] = @Kolicina, [Cena] = @Cena, [Opis] = @Opis, [Barkod] = @Barkod, [Datum] = @Datum, [Lista] = @Lista, [Prenet] = @Prenet, [DatumTerm] = @DatumTerm, [Objekat] = @Objekat, [Tabela] = @Tabela, [Dokument] = @Dokument, [Ocitavanje] = @Ocitavanje, [FakCena] = @FakCena, [Rabat] = @Rabat, [Tarifa] = @Tarifa, [Stopa] = @Stopa, [Promena] = @Promena, [Broj] = @Broj WHERE (([Term] = @Original_Term) AND ([PopisID] = @Original_PopisID));
	
SELECT Term, PopisID, Sifra, Kolicina, Cena, Opis, Barkod, Datum, Lista, Prenet, DatumTerm, SysDatum, Objekat, Tabela, Dokument, Ocitavanje, FakCena, Rabat, Tarifa, Stopa, Promena, Broj FROM PopisTerm WHERE (PopisID = @PopisID) AND (Term = @Term)

GO

/****** Object:  StoredProcedure [dbo].[PopisaTermInsert]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO




CREATE Procedure [dbo].[PopisaTermInsert] (
	 @Term varchar(3)
	, @PopisID int
	, @Sifra int
	, @Kolicina decimal(10,3)
	, @Cena decimal(9,2)
	, @Opis nvarchar(50)
	, @Barkod varchar(13)
	, @DatumTerm DATETIME
	, @Lista smallint
	, @Objekat varchar(3)
	, @Tabela VARCHAR(15)
	, @Dokument VARCHAR(15)
	, @Promena SMALLINT
	, @Broj INT
	, @Datum DATETIME
)
AS
SET NOCOUNT ON;
declare @Ocitavanje as varchar(20)
DECLARE @CenaSt AS MONEY, @FakCena NUMERIC(10,3), @Rabat NUMERIC(5,2)
DECLARE @Tarifa VARCHAR(4), @Stopa NUMERIC(5,2)
SET @CenaSt = 0

set @Ocitavanje = N'U' + convert(varchar(5), getdate(), 4) + N' ' + convert(varchar(8), getdate(), 8)
--if not exists (select Term, PopisID from PopisTerm Where Term = @Term and PopisID = @PopisID)
--BEGIN
	SET @CenaSt = 0
	SET @FakCena = 0
	SET @Tarifa = 'P1'
	Select top 1 @CenaSt = ISNULL(Cena,0), @FakCena = ISNULL(FakturnaCena, 0) from dbo.Stanje st 
		Where Sifra = @Sifra and Objekat = @Objekat
	if ISNULL(@CenaSt,0) = 0 
		set @CenaSt = @Cena
	if ISNULL(@FakCena,0) = 0 
		set @FakCena = 0
	SET @Rabat = 0
	SET @Tarifa = ISNULL((SELECT Tarifa FROM dbo.Artikli WHERE Sifra = @Sifra), 'P1')
	SET @Stopa = ISNULL((SELECT ZbirnaStopa FROM dbo.Tarife WHERE Tarifa = @Tarifa), 0)

	INSERT INTO dbo.PopisTerm (PopisID, Sifra, Kolicina, Cena, Dokument, Opis, Barkod, Objekat, Term, Lista, Datum, DatumTerm, Ocitavanje, Tabela, Promena, Broj, Tarifa, Stopa, FakCena, Rabat) 
		VALUES (@PopisID, @Sifra, @Kolicina, @CenaSt, @Dokument, @Opis, @Barkod, @Objekat, @Term, @Lista, @Datum, @DatumTerm, @Ocitavanje, @Tabela, @Promena, @Broj, @Tarifa, @Stopa, @FakCena, @Rabat)
--END

GO

/****** Object:  StoredProcedure [dbo].[PopisTermImportUDldPro]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[PopisTermImportUDldPro]
	(@Term AS VARCHAR(3), @Lista AS INT, @Promena AS SMALLINT)
AS
SET NOCOUNT ON;

DECLARE @Rbr0 INT
DECLARE @Tabela AS VARCHAR(15)
DECLARE @Broj AS INT
DECLARE @Dokument VARCHAR(20)
DECLARE @Datum DATETIME
DECLARE @Objekat VARCHAR(3)

-- pokupi sa prvog zapisa tabelu, broj, dokumenta, objekat, datum 
SELECT TOP 1 @Tabela = Tabela
		, @Broj = Broj
		, @Dokument = Dokument
		, @Objekat = Objekat
		, @Datum = Datum 
	FROM dbo.PopisTerm 
	WHERE (Lista = @Lista) AND (Term = @Term) AND (Promena = @Promena) AND (Prenet = 0)
	ORDER BY PopisID

SET @Tabela = UPPER(@Tabela)

DECLARE @tbl AS TABLE (Sifra INT NOT NULL, RedBroj int NOT NULL, Kol MONEY)
-- ZA KREIRANJE POPISA TREBA SASTAVITI SVE LISTE SA SVIH TERMINALA KOJE NISU PRENETE
IF @Tabela = 'POPIS'
	BEGIN
		SET @Rbr0 = ISNULL((SELECT MIN(PopisID) FROM dbo.PopisTerm 
			WHERE (Promena = @Promena) AND (Prenet = 0)),0) - 1
		INSERT INTO @tbl (Sifra, RedBroj, Kol)
		SELECT Sifra, MIN(PopisID) AS RBR, SUM(Kolicina) AS KOL
			FROM dbo.PopisTerm 
			WHERE (Promena = @Promena) AND (Prenet = 0)
			GROUP BY Sifra
			ORDER BY 2
	END
ELSE --Za sve ostale dokumente prenosi se prema @Lista i @Term parametru
	BEGIN
		SET @Rbr0 = ISNULL((SELECT MIN(PopisID) FROM dbo.PopisTerm WHERE (Lista = @Lista) AND (Term = @Term) AND (Promena = @Promena) AND (Prenet = 0)),0) - 1
		INSERT INTO @tbl (Sifra, RedBroj, Kol)
		SELECT Sifra, MIN(PopisID) AS RBR, SUM(Kolicina) AS KOL
			FROM dbo.PopisTerm 
			WHERE (Lista = @Lista) AND (Term = @Term) AND (Promena = @Promena) AND (Prenet = 0)
			GROUP BY Sifra
			ORDER BY 2
	END

IF @Tabela = 'KALKMP'
BEGIN
	IF @Broj = 0
		BEGIN
			-- ako je broj 0 onda kreiraj novi dokument sa vrednostima iz PopisTerm
			SET @Broj = ISNULL((SELECT MAX(Broj) FROM dbo.KalkMP0), 0) + 1
			INSERT INTO KalkMP0 (Broj, Promena, Dokument, Datum, Partner, Objekat, DatumFakture, BrFakture, Dospece, Protokol, StopaPDV, StopaPDV2, TipkPDV, TipuPDV, Knjizeno)
				VALUES (@Broj, @Promena, @Dokument, @Datum, '0000', @Objekat, @Datum, '0000', @Datum, 0 , 17 , 7 , 1 , 1 , 0)
		END
	IF (SELECT COUNT(*) FROM KalkMP0 WHERE Broj = @Broj) = 0
		BEGIN
			INSERT INTO KalkMP0 (Broj, Promena, Dokument, Datum, Partner, Objekat, DatumFakture, BrFakture, Dospece, Protokol, StopaPDV, StopaPDV2, TipkPDV, TipuPDV, Knjizeno)
				VALUES (@Broj, @Promena, @Dokument, @Datum, '0000', @Objekat, @Datum, '0000', @Datum, 0 , 17 , 7 , 1 , 1 , 0)
			--RAISERROR ('Kalkulacija nije otvorena.', 2, 1) 
			--RETURN -1;
		END
	IF (SELECT COUNT(*) FROM KalkMP0 WHERE Broj = @Broj AND Knjizeno <> 0) > 0
		BEGIN
			RAISERROR ('Kalkulacija je proknjižena, nije moguće dodatavi stake u knjiženi dokument', 2, 1) 
			RETURN -1;
		END

	--Kalkulacije MP                      	
	INSERT INTO dbo.KalkMp
			( Broj ,
			  RedBroj ,
			  Sifra ,
			  -- Naziv ,
			  -- Barkod ,
			  Tarifa ,
			  Kolicina ,
			  Komada ,
			  FakCena ,
			  Rabat ,
			  NabCena ,
			  Cena ,
			  PrCenaKom ,
			  Stopa ,
			  Republicki ,
			  r_izn ,
			  pdr_izn ,
			  Knjizeno ,
			  Protokol ,
			  StopaPDV 
			)
	SELECT Broj ,
			  t.RedBroj - @Rbr0 as RedBroj ,
			  p.Sifra ,
			  -- Opis Naziv ,
			  -- Barkod ,
			  Tarifa ,
			  t.Kol Kolicina ,
			  t.Kol as Komada ,
			  FakCena ,
			  Rabat ,
			  FakCena * (1 - (Rabat / 100)) as NabCena ,
			  Cena ,
			  Cena PrCenaKom ,
			  Stopa ,
			  Stopa Republicki ,
			  ROUND((t.Kol * Cena) * (Stopa / (100 + Stopa)), 2) r_izn ,
			  ROUND(((t.Kol * FakCena) * (1 - (Rabat / 100))) * (Stopa / 100),2) pdr_izn ,
			  0 Knjizeno ,
			  0 Protokol ,
			  Stopa StopaPDV 
	FROM dbo.PopisTerm P INNER JOIN @tbl t 
		ON P.Sifra = t.Sifra AND p.PopisID = t.RedBroj
	WHERE (Lista = @Lista) AND (Term = @Term) AND (Promena = @Promena) AND (Prenet = 0);
END
--Kalkulacije VP
IF @Tabela = 'KALK'
BEGIN
	IF @Broj = 0
		BEGIN
			-- ako je broj 0 onda kreiraj novi dokument sa vrednostima iz PopisTerm
			SET @Broj = ISNULL((SELECT MAX(Broj) FROM dbo.Kalk0), 0) + 1
			INSERT INTO Kalk0 (Broj, Promena, Dokument, Datum, Partner, Objekat, DatumFakture, BrFakture, Dospece, Protokol, StopaPDV, StopaPDV2, TipkPDV, TipuPDV, Knjizeno)
				VALUES (@Broj, @Promena, @Dokument, @Datum, '0000', @Objekat, @Datum, '0000', @Datum, 0 , 17 , 7 , 1 , 1 , 0)

		END
	IF (SELECT COUNT(*) FROM Kalk0 WHERE Broj = @Broj) = 0
		BEGIN
			INSERT INTO Kalk0 (Broj, Promena, Dokument, Datum, Partner, Objekat, DatumFakture, BrFakture, Dospece, Protokol, StopaPDV, StopaPDV2, TipkPDV, TipuPDV, Knjizeno)
				VALUES (@Broj, @Promena, @Dokument, @Datum, '0000', @Objekat, @Datum, '0000', @Datum, 0 , 17 , 7 , 1 , 1 , 0)
			--RAISERROR ('Kalkulacija nije otvorena.', 2, 1) 
			--RETURN -1;
		END
	IF (SELECT COUNT(*) FROM Kalk0 WHERE Broj = @Broj AND Knjizeno <> 0) > 0
		BEGIN
			RAISERROR ('Kalkulacija je proknjižena, nije moguće dodatavi stake u knjiženi dokument', 2, 1) 
			RETURN -1;
		END

	INSERT INTO dbo.Kalk
			( Broj ,
			  RedBroj ,
			  Sifra ,
			  Tarifa ,
			  Kolicina ,
			  FakCena ,
			  Rabat ,
			  NabCena ,
			  Cena ,
			  Stopa ,
			  Republicki ,
			  r_izn ,
			  pdr_izn ,
			  Knjizeno ,
			  Protokol ,
			  StopaPDV 
			)
	SELECT Broj ,
			  t.RedBroj - @Rbr0 as RedBroj ,
			  p.Sifra ,
			  Tarifa ,
			  t.Kol Kolicina ,
			  FakCena ,
			  Rabat ,
			  FakCena * (1 - (Rabat / 100)) as NabCena ,
			  Cena ,
			  Stopa ,
			  Stopa Republicki ,
			  ROUND((t.Kol * Cena) * (Stopa / (100 + Stopa)), 2) r_izn ,
			  ROUND(((t.Kol * FakCena) * (1 - (Rabat / 100))) * (Stopa / 100),2) pdr_izn ,
			  0 Knjizeno ,
			  0 Protokol ,
			  Stopa StopaPDV 
	FROM dbo.PopisTerm P INNER JOIN @tbl t 
		ON P.Sifra = t.Sifra AND p.PopisID = t.RedBroj
	WHERE (Lista = @Lista) AND (Term = @Term) AND (Promena = @Promena) AND (Prenet = 0);
END
-- popis 
IF @Tabela = 'POPIS'
BEGIN
	--Kreiranje Popisa
	IF @Broj = 0
		BEGIN
			-- ako je broj 0 onda kreiraj novi dokument sa vrednostima iz PopisTerm
			SET @Broj = ISNULL((SELECT MAX(Broj) FROM dbo.Popis0), 0) + 1
			INSERT INTO dbo.Popis0
			        ( Broj ,
			          Objekat ,
			          Datum ,
			          Dokument ,
			          Iznos ,
			          Knjizeno ,
			          Protokol ,
			          Popis ,
			          Promena ,
			          Operater
			        )
			VALUES  ( @Broj , -- Broj - int
			          @Objekat , -- Objekat - nvarchar(3)
			          @Datum , -- Datum - datetime
			          @Dokument , -- Dokument - nvarchar(10)
			          0 , -- Iznos - money
			          0 , -- Knjizeno - bit
			          0 , -- Protokol - int
			          1 , -- Popis - bit
			          @Promena , -- Promena - int
			          0  -- Operater - int
			        )
		END
	IF (SELECT COUNT(*) FROM Popis0 WHERE Broj = @Broj) = 0
		BEGIN
			INSERT INTO dbo.Popis0
			        ( Broj ,
			          Objekat ,
			          Datum ,
			          Dokument ,
			          Iznos ,
			          Knjizeno ,
			          Protokol ,
			          Popis ,
			          Promena ,
			          Operater
			        )
			VALUES  ( @Broj , -- Broj - int
			          @Objekat , -- Objekat - nvarchar(3)
			          @Datum , -- Datum - datetime
			          @Dokument , -- Dokument - nvarchar(10)
			          0 , -- Iznos - money
			          0 , -- Knjizeno - bit
			          0 , -- Protokol - int
			          1 , -- Popis - bit
			          @Promena , -- Promena - int
			          0  -- Operater - int
			        )
			--RAISERROR ('Popis nije otvorena.', 2, 1) 
			--RETURN -1;
		END
	IF (SELECT COUNT(*) FROM dbo.Popis0 WHERE Broj = @Broj AND Knjizeno <> 0) > 0
		BEGIN
			RAISERROR ('Popis je proknjižena, nije moguće dodatavi stake u knjiženi dokument', 2, 1) 
			RETURN -1;
		END

	INSERT INTO dbo.Popis
			( Broj ,
			  RedBroj ,
			  Sifra ,
			  Tarifa ,
			  Kolicina ,
			  NabCena ,
			  Cena ,
			  Stopa ,
			  Protokol,
			  KKolicina,
			  KCena,
			  kIznos --, 
			  -- Barkod , --Ovo je ako ima u tabeli barkod i naziv
			  --Naziv
			)
	SELECT Broj ,
			  t.RedBroj - @Rbr0 as RedBroj ,
			  p.Sifra ,
			  Tarifa ,
			  t.Kol Kolicina ,
			  FakCena as NabCena ,
			  Cena ,
			  Stopa ,
			  0 Protokol ,
			  0 KKolicina,
			  0 KCena,
			  0 KIznos --,
			  --Barkod, --Ovo je ako ima u tabeli barkod i naziv
			  --Opis
	FROM dbo.PopisTerm P INNER JOIN @tbl t 
		ON P.Sifra = t.Sifra AND p.PopisID = t.RedBroj
	WHERE (Promena = @Promena) AND (Prenet = 0);
	UPDATE dbo.Popis SET KKolicina = o.Zalihe, KCena = o.Cena 
		FROM (SELECT Sifra AS sif, Zalihe, Cena 
				FROM Stanje WHERE Objekat = @Objekat) o
		WHERE Sifra = o.Sif;
	
END
-- Račun VP
IF @Tabela = 'RACUN'
BEGIN
	IF @Broj = 0
		BEGIN
			-- ako je broj 0 onda kreiraj novi dokument sa vrednostima iz PopisTerm
			SET @Broj = ISNULL((SELECT MAX(Broj) FROM dbo.Racun0), 0) + 1
			INSERT INTO Racun0 (Broj, Promena, Dokument, Datum, Partner, Objekat, Valuta, Protokol, TipkPDV, TipuPDV, Knjizeno, SaPorezom, Placanje)
				VALUES (@Broj, @Promena, @Dokument, @Datum, '0000', @Objekat, @Datum, 0 , 1 , 1 , 0, 1, 1)

		END
	IF (SELECT COUNT(*) FROM dbo.Racun0 WHERE Broj = @Broj) = 0
		BEGIN
			INSERT INTO Racun0 (Broj, Promena, Dokument, Datum, Partner, Objekat, Valuta, Protokol, TipkPDV, TipuPDV, Knjizeno, SaPorezom, Placanje)
				VALUES (@Broj, @Promena, @Dokument, @Datum, '0000', @Objekat, @Datum, 0 , 1 , 1 , 0, 1, 1)
			--RAISERROR ('Račun nije otvorena.', 2, 1) 
			--RETURN -1;
		END
	IF (SELECT COUNT(*) FROM dbo.Racun0 WHERE Broj = @Broj AND Knjizeno <> 0) > 0
		BEGIN
			RAISERROR ('Račun je proknjižen, nije moguće dodatavi stake u knjiženi dokument', 2, 1) 
			RETURN -1;
		END

	INSERT INTO dbo.Racun
			( Broj ,
			  RedBroj ,
			  Sifra ,
			  Tarifa ,
			  Kolicina ,
			  Rabat ,
			  NabCena ,
			  Cena ,
			  Iznos, 
			  Stopa ,
			  Knjizeno ,
			  Protokol ,
			  Porez
			)
	SELECT Broj ,
			  t.RedBroj - @Rbr0 as RedBroj ,
			  p.Sifra ,
			  Tarifa ,
			  t.Kol Kolicina ,
			  Rabat ,
			  FakCena as NabCena ,
			  Cena ,
			  ROUND(t.Kol * Cena, 2) AS Iznos,
			  Stopa ,
			  0 Knjizeno ,
			  0 Protokol ,
			  1 Porez 
	FROM dbo.PopisTerm P INNER JOIN @tbl t 
		ON P.Sifra = t.Sifra AND p.PopisID = t.RedBroj
	WHERE (Lista = @Lista) AND (Term = @Term) AND (Promena = @Promena) AND (Prenet = 0);
END
-- Račun MP tabela Izlaz
IF @Tabela = 'IZLAZ'
BEGIN
	IF @Broj = 0
		BEGIN
			-- ako je broj 0 onda kreiraj novi dokument sa vrednostima iz PopisTerm
			SET @Broj = ISNULL((SELECT MAX(Broj) FROM dbo.Izlaz0), 0) + 1
			INSERT INTO Izlaz0 (Broj, Promena, Dokument, Datum, Partner, Objekat, Valuta, Protokol, TipkPDV, TipuPDV, Knjizeno, Placanje)
				VALUES (@Broj, @Promena, @Dokument, @Datum, '0000', @Objekat, @Datum, 0, 1, 1, 0, 1)

		END
	IF (SELECT COUNT(*) FROM dbo.Izlaz0 WHERE Broj = @Broj) = 0
		BEGIN
			INSERT INTO Izlaz0 (Broj, Promena, Dokument, Datum, Partner, Objekat, Valuta, Protokol, TipkPDV, TipuPDV, Knjizeno, Placanje)
				VALUES (@Broj, @Promena, @Dokument, @Datum, '0000', @Objekat, @Datum, 0, 1, 1, 0, 1)
			--RAISERROR ('Račun MP nije otvorena.', 2, 1) 
			--RETURN -1;
		END
	IF (SELECT COUNT(*) FROM dbo.Izlaz0 WHERE Broj = @Broj AND Knjizeno <> 0) > 0
		BEGIN
			RAISERROR ('Račun je proknjižen, nije moguće dodatavi stake u knjiženi dokument', 2, 1) 
			RETURN -1;
		END

	INSERT INTO dbo.Izlaz
			( Broj ,
			  RedBroj ,
			  Sifra ,
			  Tarifa ,
			  Kolicina ,
			  Rabat ,
			  NabCena ,
			  Cena ,
			  Iznos, 
			  Stopa ,
			  Knjizeno ,
			  Protokol ,
			  Porez
			)
	SELECT Broj ,
			  t.RedBroj - @Rbr0 as RedBroj ,
			  p.Sifra ,
			  Tarifa ,
			  t.Kol Kolicina ,
			  Rabat ,
			  FakCena as NabCena ,
			  Cena ,
			  ROUND(t.Kol * Cena, 2) AS Iznos,
			  Stopa ,
			  0 Knjizeno ,
			  0 Protokol ,
			  1 Porez 
	FROM dbo.PopisTerm P INNER JOIN @tbl t 
		ON P.Sifra = t.Sifra AND p.PopisID = t.RedBroj
	WHERE (Lista = @Lista) AND (Term = @Term) AND (Promena = @Promena) AND (Prenet = 0);
	--azuriraj broj kako bi ga markirao u tabeli popis
	UPDATE dbo.PopisTerm SET Broj = @Broj 
		WHERE (Lista = @Lista) AND (Term = @Term) AND (Promena = @Promena) AND (Prenet = 0);
	
END
-- Nivelacija MP
IF @Tabela = 'NIVELMP'
BEGIN
	--Kreiranje Nivelacije
	IF @Broj = 0
		BEGIN
			-- ako je broj 0 onda kreiraj novi dokument sa vrednostima iz PopisTerm
			SET @Broj = ISNULL((SELECT MAX(Broj) FROM dbo.NivelMP0), 0) + 1
			INSERT INTO dbo.NivelMP0
			        ( Broj ,
			          Objekat ,
			          Datum ,
			          Dokument ,
			          Iznos ,
			          Knjizeno ,
			          Protokol ,
			          Popis ,
			          Promena ,
			          Operater
			        )
			VALUES  ( @Broj , -- Broj - int
			          @Objekat , -- Objekat - nvarchar(3)
			          @Datum , -- Datum - datetime
			          @Dokument , -- Dokument - nvarchar(10)
			          0 , -- Iznos - money
			          0 , -- Knjizeno - bit
			          0 , -- Protokol - int
			          0 , -- Popis - bit
			          @Promena , -- Promena - int
			          0  -- Operater - int
			        )
		END
	IF (SELECT COUNT(*) FROM dbo.NivelMP0 WHERE Broj = @Broj) = 0
		BEGIN
			INSERT INTO dbo.NivelMP0
			        ( Broj ,
			          Objekat ,
			          Datum ,
			          Dokument ,
			          Iznos ,
			          Knjizeno ,
			          Protokol ,
			          Popis ,
			          Promena ,
			          Operater
			        )
			VALUES  ( @Broj , -- Broj - int
			          @Objekat , -- Objekat - nvarchar(3)
			          @Datum , -- Datum - datetime
			          @Dokument , -- Dokument - nvarchar(10)
			          0 , -- Iznos - money
			          0 , -- Knjizeno - bit
			          0 , -- Protokol - int
			          0 , -- Popis - bit
			          @Promena , -- Promena - int
			          0  -- Operater - int
			        )
			--RAISERROR ('Nivelacija nije otvorena.', 2, 1) 
			--RETURN -1;
		END
	IF (SELECT COUNT(*) FROM dbo.NivelMP0 WHERE Broj = @Broj AND Knjizeno <> 0) > 0
		BEGIN
			RAISERROR ('Nivelacija je proknjižena, nije moguće dodatavi stake u knjiženi dokument', 2, 1) 
			RETURN -1;
		END

	INSERT INTO dbo.NivelMP
			( Broj ,
			  RedBroj ,
			  Sifra ,
			  Tarifa ,
			  Kolicina ,
			  NabCena ,
			  Cena ,
			  Stopa ,
			  Protokol,
			  KKolicina,
			  KCena
			)
	SELECT Broj ,
			  t.RedBroj - @Rbr0 as RedBroj ,
			  p.Sifra ,
			  Tarifa ,
			  t.Kol Kolicina ,
			  FakCena as NabCena ,
			  Cena ,
			  Stopa ,
			  0 Protokol ,
			  0 KKolicina,
			  Cena KCena
	FROM dbo.PopisTerm P INNER JOIN @tbl t 
		ON P.Sifra = t.Sifra AND p.PopisID = t.RedBroj
	WHERE (Lista = @Lista) AND (Term = @Term) AND (Promena = @Promena) AND (Prenet = 0);
	UPDATE dbo.NivelMP SET KKolicina = o.Zalihe, KCena = o.Cena 
		FROM (SELECT Sifra AS sif, Zalihe, Cena 
				FROM Stanje WHERE Objekat = @Objekat) o
		WHERE Sifra = o.Sif;
END
-- Nivelacija VP
IF @Tabela = 'NIVEL'
BEGIN
	--Kreiranje Nivelacije
	IF @Broj = 0
		BEGIN
			-- ako je broj 0 onda kreiraj novi dokument sa vrednostima iz PopisTerm
			SET @Broj = ISNULL((SELECT MAX(Broj) FROM dbo.Nivel0), 0) + 1
			INSERT INTO dbo.Nivel0
			        ( Broj ,
			          Objekat ,
			          Datum ,
			          Dokument ,
			          Iznos ,
			          Knjizeno ,
			          Protokol ,
			          Popis ,
			          Promena ,
			          Operater
			        )
			VALUES  ( @Broj , -- Broj - int
			          @Objekat , -- Objekat - nvarchar(3)
			          @Datum , -- Datum - datetime
			          @Dokument , -- Dokument - nvarchar(10)
			          0 , -- Iznos - money
			          0 , -- Knjizeno - bit
			          0 , -- Protokol - int
			          0 , -- Popis - bit
			          @Promena , -- Promena - int
			          0  -- Operater - int
			        )
		END
	IF (SELECT COUNT(*) FROM dbo.Nivel0 WHERE Broj = @Broj) = 0
		BEGIN
			INSERT INTO dbo.Nivel0
			        ( Broj ,
			          Objekat ,
			          Datum ,
			          Dokument ,
			          Iznos ,
			          Knjizeno ,
			          Protokol ,
			          Popis ,
			          Promena ,
			          Operater
			        )
			VALUES  ( @Broj , -- Broj - int
			          @Objekat , -- Objekat - nvarchar(3)
			          @Datum , -- Datum - datetime
			          @Dokument , -- Dokument - nvarchar(10)
			          0 , -- Iznos - money
			          0 , -- Knjizeno - bit
			          0 , -- Protokol - int
			          0 , -- Popis - bit
			          @Promena , -- Promena - int
			          0  -- Operater - int
			        )
			--RAISERROR ('Nivelacija nije otvorena.', 2, 1) 
			--RETURN -1;
		END
	IF (SELECT COUNT(*) FROM dbo.Nivel0 WHERE Broj = @Broj AND Knjizeno <> 0) > 0
		BEGIN
			RAISERROR ('Nivelacija je proknjižena, nije moguće dodatavi stake u knjiženi dokument', 2, 1) 
			RETURN -1;
		END

	INSERT INTO dbo.Nivel
			( Broj ,
			  RedBroj ,
			  Sifra ,
			  Tarifa ,
			  Kolicina ,
			  NabCena ,
			  Cena ,
			  Stopa ,
			  Protokol,
			  KKolicina,
			  KCena
			)
	SELECT Broj ,
			  t.RedBroj - @Rbr0 as RedBroj ,
			  p.Sifra ,
			  Tarifa ,
			  t.Kol Kolicina ,
			  FakCena as NabCena ,
			  Cena ,
			  Stopa ,
			  0 Protokol ,
			  0 KKolicina,
			  Cena KCena
	FROM dbo.PopisTerm P INNER JOIN @tbl t 
		ON P.Sifra = t.Sifra AND p.PopisID = t.RedBroj
	WHERE (Lista = @Lista) AND (Term = @Term) AND (Promena = @Promena) AND (Prenet = 0);
	UPDATE dbo.NivelMP SET KKolicina = o.Zalihe, KCena = o.Cena 
		FROM (SELECT Sifra AS sif, Zalihe, Cena 
				FROM Stanje WHERE Objekat = @Objekat) o
		WHERE Sifra = o.Sif;
END



IF @Tabela = 'POPIS'
	UPDATE dbo.PopisTerm SET Prenet = 1 WHERE (Promena = @Promena) AND (Prenet = 0);
ELSE
	UPDATE dbo.PopisTerm SET Prenet = 1 WHERE (Lista = @Lista) AND (Term = @Term) AND (Promena = @Promena) AND (Prenet = 0);

RETURN

GO

/****** Object:  StoredProcedure [dbo].[PopisTermSelectByLista]    Script Date: 05/12/2010 09:26:22 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[PopisTermSelectByLista]
	@Term VARCHAR(3), @Lista AS INT
AS
SET @Term = ISNULL(@Term, '')
SET @Lista = ISNULL(@Lista, 0)
IF @Lista <> 0 AND @Term <> ''
	SELECT Term ,
			PopisID ,
			Sifra ,
			Kolicina ,
			Cena ,
			Opis ,
			Barkod ,
			Datum ,
			Lista ,
			Prenet ,
			DatumTerm ,
			SysDatum ,
			Objekat ,
			Tabela ,
			Dokument ,
			Ocitavanje ,
			FakCena ,
			Rabat ,
			Tarifa ,
			Stopa ,
			Promena ,
			Broj
	FROM         PopisTerm
	WHERE Term = @Term AND Lista = @Lista AND Prenet = 0
	ORDER BY PopisID
IF @Lista = 0 AND @Term = ''
	SELECT Term ,
			PopisID ,
			Sifra ,
			Kolicina ,
			Cena ,
			Opis ,
			Barkod ,
			Datum ,
			Lista ,
			Prenet ,
			DatumTerm ,
			SysDatum ,
			Objekat ,
			Tabela ,
			Dokument ,
			Ocitavanje ,
			FakCena ,
			Rabat ,
			Tarifa ,
			Stopa ,
			Promena ,
			Broj
	FROM         PopisTerm
	WHERE Prenet = 0
	ORDER BY PopisID
ELSE IF @Term = '' AND @Lista <> 0  
	SELECT Term ,
			PopisID ,
			Sifra ,
			Kolicina ,
			Cena ,
			Opis ,
			Barkod ,
			Datum ,
			Lista ,
			Prenet ,
			DatumTerm ,
			SysDatum ,
			Objekat ,
			Tabela ,
			Dokument ,
			Ocitavanje ,
			FakCena ,
			Rabat ,
			Tarifa ,
			Stopa ,
			Promena ,
			Broj
	FROM         PopisTerm
	WHERE Lista = @Lista  AND Prenet = 0
	ORDER BY PopisID	
ELSE IF @Lista = 0 AND @Term <> ''
	SELECT Term ,
			PopisID ,
			Sifra ,
			Kolicina ,
			Cena ,
			Opis ,
			Barkod ,
			Datum ,
			Lista ,
			Prenet ,
			DatumTerm ,
			SysDatum ,
			Objekat ,
			Tabela ,
			Dokument ,
			Ocitavanje ,
			FakCena ,
			Rabat ,
			Tarifa ,
			Stopa ,
			Promena ,
			Broj
	FROM         PopisTerm
	WHERE Term = @Term   AND Prenet = 0
	ORDER BY PopisID
GO

CREATE        PROCEDURE [dbo].[pos2_ArtikliDan]
	(
		@Datum datetime ,
		@Placanje smallint = 2
	)
AS
	SET NOCOUNT ON
	declare @strDat0 as nvarchar(10)
	declare @strDat1 as nvarchar(10)
	declare @Dat0 as datetime
	declare @Dat1 as datetime
	
	set @strDat0 = convert(nvarchar(10), @Datum, 126)
	set @strDat1 = convert(nvarchar(10), DateAdd(d, 1, @Datum), 126)
	set @Dat0 = convert(datetime, @strDat0 + ' 04:59:59', 102)
	set @Dat1 = convert(datetime, @strDat1 + ' 05:00:00', 102)
	DECLARE @Dat as nvarchar(10)
	SET @Dat = convert(nvarchar(10), @Datum, 102);
	if @Placanje = 1 BEGIN
	-- RACUN FAKTURE POJEDINAČNO
		SELECT     dbo.DateValue(dbo.KasaFP.Datum) AS Datum, dbo.KasaFP.Dokument, dbo.KasaFP.Broj, dbo.KasaFP.Placanje, dbo.KasaFP.Partner, dbo.KasaFPSt.Sifra, dbo.KasaFPSt.Cena, dbo.KasaFPSt.Stopa, dbo.KasaFPSt.TarifaA,  SUM(dbo.KasaFPSt.kolicina) AS kolicina,
							SUM(dbo.KasaFPSt.Kolicina * dbo.KasaFPSt.Cena) AS iznos, SUM((dbo.KasaFPSt.kolicina * dbo.KasaFPSt.cena) * (cast(dbo.KasaFPSt.Rabat as Money) / 100)) AS popust, cast(dbo.KasaFPSt.Rabat as smallmoney) as Rabat
		FROM         dbo.KasaFPSt INNER JOIN
							dbo.KasaFP ON dbo.KasaFPSt.Kasa = dbo.KasaFP.Kasa AND dbo.KasaFPSt.Broj = dbo.KasaFP.Broj
		WHERE    ((dbo.KasaFP.ZakljucenDan) <> 0 AND (dbo.KasaFP.Stornirano = 0)) and (dbo.KasaFP.Placanje = @Placanje) AND (dbo.KasaFP.Datum BETWEEN @Dat0 AND @Dat1)
		GROUP BY dbo.DateValue(dbo.KasaFP.Datum), dbo.KasaFP.Dokument, dbo.KasaFP.Broj, dbo.KasaFP.Placanje, dbo.KasaFP.Partner, dbo.KasaFPSt.Sifra, dbo.KasaFPSt.Cena, dbo.KasaFPSt.Stopa, dbo.KasaFPSt.TarifaA, dbo.KasaFPSt.Rabat
		ORDER BY dbo.KasaFPSt.Sifra
	END
	if @Placanje = 3 BEGIN
	-- KARTICE PO VRSTI
		SELECT     dbo.DateValue(dbo.KasaFP.Datum) AS Datum, CAST(N'C0000' AS nvarchar(10)) as Dokument, dbo.KasaFP.Placanje, dbo.KasaFP.Partner, dbo.KasaFPSt.Sifra, dbo.KasaFPSt.Cena, dbo.KasaFPSt.Stopa, dbo.KasaFPSt.TarifaA, SUM(dbo.KasaFPSt.kolicina) AS kolicina,
							SUM(dbo.KasaFPSt.Kolicina * dbo.KasaFPSt.Cena) AS iznos, SUM((dbo.KasaFPSt.kolicina * dbo.KasaFPSt.cena) * (cast(dbo.KasaFPSt.Rabat as Money) / 100)) AS popust, cast(dbo.KasaFPSt.Rabat as smallmoney) as Rabat
		FROM         dbo.KasaFPSt INNER JOIN
							dbo.KasaFP ON dbo.KasaFPSt.Kasa = dbo.KasaFP.Kasa AND dbo.KasaFPSt.Broj = dbo.KasaFP.Broj
		WHERE   ((dbo.KasaFP.ZakljucenDan) <> 0 AND (dbo.KasaFP.Stornirano = 0)) AND  (dbo.KasaFP.Placanje = @Placanje) AND (dbo.KasaFP.Datum BETWEEN @Dat0 AND @Dat1)
		GROUP BY dbo.DateValue(dbo.KasaFP.Datum), dbo.KasaFP.Placanje, dbo.KasaFP.Partner, dbo.KasaFPSt.Sifra, dbo.KasaFPSt.Cena, dbo.KasaFPSt.Stopa, dbo.KasaFPSt.TarifaA, dbo.KasaFPSt.Rabat	
		ORDER BY dbo.KasaFPSt.Sifra
	END
	if @Placanje = 4 BEGIN
	-- kredit po partneru zbirno
		SELECT     dbo.DateValue(dbo.KasaFP.Datum) AS Datum, CAST(N'K0000' AS nvarchar(10)) as Dokument, dbo.KasaFP.Placanje, dbo.KasaFP.Partner, dbo.KasaFPSt.Sifra, dbo.KasaFPSt.Cena, dbo.KasaFPSt.Stopa, dbo.KasaFPSt.TarifaA, SUM(dbo.KasaFPSt.kolicina) AS kolicina,
							SUM(dbo.KasaFPSt.Kolicina * dbo.KasaFPSt.Cena) AS iznos, SUM((dbo.KasaFPSt.kolicina * dbo.KasaFPSt.cena) * (cast(dbo.KasaFPSt.Rabat as Money) / 100)) AS popust, cast(dbo.KasaFPSt.Rabat as smallmoney) as Rabat
		FROM         dbo.KasaFPSt INNER JOIN
							dbo.KasaFP ON dbo.KasaFPSt.Kasa = dbo.KasaFP.Kasa AND dbo.KasaFPSt.Broj = dbo.KasaFP.Broj
		WHERE    ((dbo.KasaFP.ZakljucenDan) <> 0 AND (dbo.KasaFP.Stornirano = 0)) AND (dbo.KasaFP.Placanje = @Placanje) AND (dbo.KasaFP.Datum BETWEEN @Dat0 AND @Dat1)
		GROUP BY dbo.DateValue(dbo.KasaFP.Datum), dbo.KasaFP.Placanje, dbo.KasaFP.Partner, dbo.KasaFPSt.Sifra, dbo.KasaFPSt.Cena, dbo.KasaFPSt.Stopa, dbo.KasaFPSt.TarifaA, dbo.KasaFPSt.Rabat	
		ORDER BY dbo.KasaFPSt.Sifra
	END
	if @Placanje = 2 BEGIN
	-- GOTOVINA SAMO ZBIRNO
		SELECT     dbo.DateValue(dbo.KasaFP.Datum) AS Datum, CAST(N'00000' AS nvarchar(10)) as Dokument, dbo.KasaFP.Placanje, dbo.KasaFP.Partner, dbo.KasaFPSt.Sifra, dbo.KasaFPSt.Cena, dbo.KasaFPSt.Stopa, dbo.KasaFPSt.TarifaA, SUM(dbo.KasaFPSt.kolicina) AS kolicina,
							SUM(dbo.KasaFPSt.Kolicina * dbo.KasaFPSt.Cena) AS iznos, SUM((dbo.KasaFPSt.kolicina * dbo.KasaFPSt.cena) * (cast(dbo.KasaFPSt.Rabat as Money) / 100)) AS popust, cast(dbo.KasaFPSt.Rabat as smallmoney) as Rabat
		FROM         dbo.KasaFPSt INNER JOIN
							dbo.KasaFP ON dbo.KasaFPSt.Kasa = dbo.KasaFP.Kasa AND dbo.KasaFPSt.Broj = dbo.KasaFP.Broj
		WHERE    ((dbo.KasaFP.ZakljucenDan) <> 0 AND (dbo.KasaFP.Stornirano = 0)) AND (dbo.KasaFP.Placanje = @Placanje) AND (dbo.KasaFP.Datum BETWEEN @Dat0 AND @Dat1)
		GROUP BY dbo.DateValue(dbo.KasaFP.Datum), dbo.KasaFP.Placanje, dbo.KasaFP.Partner, dbo.KasaFPSt.Sifra, dbo.KasaFPSt.Cena, dbo.KasaFPSt.Stopa, dbo.KasaFPSt.TarifaA, dbo.KasaFPSt.Rabat	
		ORDER BY dbo.KasaFPSt.Sifra
	END
	RETURN

GO

-- trigeri
-- triger za zaključenja
/****** Object:  Trigger [trgZakljucenjaInsert]    Script Date: 04/06/2010 14:23:29 ******/
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[trgZakljucenjaInsert]'))
DROP TRIGGER [dbo].[trgZakljucenjaInsert]
GO

IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[trgZakljucenjaInsert]'))
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:		Dejan Dabić
-- Create date: 25.03.2010
-- Description:	Insert triger za zaključenje, zaključuju se i svi fiskalni računi koji pripadaju ovom zaključenju
-- =============================================
CREATE TRIGGER [dbo].[trgZakljucenjaInsert] 
   ON  [dbo].[Zakljucenja] 
   AFTER INSERT
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @Kasa VARCHAR(3), @Zakljucenje INT
	SELECT TOP 1 @Kasa = Kasa, @Zakljucenje = Zakljucenje 
		FROM inserted z
	IF	@Zakljucenje IS NULL
		RETURN;
	-- Prepis u KasaArhB0 
	INSERT INTO dbo.KasaArhB0
	        ( Kasa ,
	          Broj ,
	          Objekat ,
	          Dokument ,
	          Datum ,
	          Iznos ,
	          IznosPDV ,
	          Placanje ,
	          Promena ,
	          Partner ,
	          Smena ,
	          Operater ,
	          SysDatum ,
	          Poslat ,
	          Iznos2 ,
	          Opis,
	          Faktura
	        )
	SELECT Kasa , -- Kasa - nvarchar(3)
	          Broj , -- Broj - int
	          Objekat , -- Objekat - nvarchar(3)
	          Dokument , -- Dokument - nvarchar(10)
	          Datum , -- Datum - datetime
	          Iznos , -- Iznos - money
	          IznosPDV , -- IznosPDV - money
	          Placanje , -- Placanje - smallint
	          Promena , -- Promena - smallint
	          Partner , -- Partner - nvarchar(6)
	          Zakljucenje , -- Smena - int
	          Operater , -- Operater - smallint
	          SysDatum , -- SysDatum - datetime
	          0 , -- Poslat - tinyint
	          Iznos2 , -- Iznos2 - money
	          Opis,  -- Opis - nvarchar(60)
	          Faktura
	        FROM dbo.KasaFP k
	        WHERE Kasa = @Kasa
				AND Zakljucenje = @Zakljucenje 
				AND ZakljucenDan = 0 AND Faktura IS NULL;
	INSERT INTO dbo.KasaArhB
	        ( Kasa ,
	          Broj ,
	          RedBroj ,
	          Sifra ,
	          kolicina ,
	          cena ,
	          iznos ,
	          rabat ,
	          TarifaA ,
	          Stopa
	        )
	SELECT Kasa , -- Kasa - nvarchar(3)
	          Broj , -- Broj - int
	          RedBroj , -- RedBroj - smallint
	          Sifra , -- Sifra - int
	          Kolicina , -- kolicina - money
	          Cena , -- cena - money
	          Round(Kolicina * Cena, 2) , -- iznos - money
	          Rabat , -- rabat - smallint
	          TarifaA , -- TarifaA - nvarchar(1)
	          Stopa  -- Stopa - tinyint
	        FROM dbo.KasaFPSt kst
	        WHERE Broj IN 
				(SELECT Broj FROM KasaFP 
				WHERE Kasa = @Kasa
					AND Zakljucenje = @Zakljucenje 
					AND ZakljucenDan = 0
					AND Faktura IS NULL);
	-- označi kao zaključen dan
	UPDATE dbo.KasaFP SET ZakljucenDan = 1 
		WHERE Kasa = @Kasa 
			AND Zakljucenje = @Zakljucenje
			AND ZakljucenDan = 0;

END

' 
GO
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[trgArtikliFPInsert]'))
DROP TRIGGER [dbo].[trgArtikliFPInsert]
GO

-- =============================================
-- Author:		Dejan
-- Create date: 9.11.2009
-- Description:	Azuraira PLU za novi uneti artikal u tabelu ArtikliFP
-- =============================================
CREATE TRIGGER [dbo].[trgArtikliFPInsert] 
   ON  [dbo].[ArtikliFP] 
   AFTER INSERT
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	insert into ArtikliPlu (Sifra) 
		Select i.Sifra from Inserted i 
		where not i.Sifra in (Select Sifra from ArtikliPlu) AND ((i.Plu is null) or (i.Plu = 0))
		Order by i.Sifra
	update ArtikliFP set ArtikliFP.Plu = a.Plu 
		From ArtikliPlu a inner join inserted i on a.Sifra = i.Sifra
		where ArtikliFP.Sifra = a.Sifra and ((ArtikliFP.Plu is null) or (ArtikliFP.Plu = 0))

END

GO
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[trgArtikliUpdateBarkod]'))
DROP TRIGGER [dbo].[trgArtikliUpdateBarkod]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Dejan
-- Create date: 2010-06-15
-- Description:	Ažuriranje Barkodova u ArtikliFP
-- =============================================
CREATE TRIGGER [dbo].[trgArtikliUpdateBarkod] 
   ON  [dbo].[Artikli] 
   AFTER UPDATE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	IF UPDATE(Barkod)
	BEGIN
		UPDATE dbo.ArtikliFP SET Barkod = i.Barkod 
		FROM INSERTED i 
		WHERE dbo.ArtikliFP.Sifra = i.Sifra
	END
	IF UPDATE(NazivArtikla)
	BEGIN
		UPDATE dbo.ArtikliFP SET NazivArtikla = i.NazivArtikla 
		FROM INSERTED i 
		WHERE dbo.ArtikliFP.Sifra = i.Sifra
	END
END

GO



IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[trgKalkMp0UpdateKnjizeno]'))
DROP TRIGGER [dbo].[trgKalkMp0UpdateKnjizeno]
GO
-- =============================================
-- Author:		Dejan
-- Create date: 10.4.2010
-- Description:	Okida ažuriranje ArtikliFP kad se proknjiži kalkulacija
-- =============================================
CREATE TRIGGER dbo.trgKalkMp0UpdateKnjizeno 
   ON  dbo.KalkMP0 
   AFTER UPDATE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	IF UPDATE(Knjizeno)
	BEGIN
		BEGIN TRY
			DECLARE @Broj AS INT
			DECLARE @Knj AS BIT
			DECLARE @Obj AS NVARCHAR(6)
			DECLARE @RC int
			SELECT TOP 1 @Broj = i.Broj, @Knj = i.Knjizeno, @Obj = i.Objekat 
				FROM INSERTED i
			IF @Broj IS NULL
				RETURN
			IF @Knj = 0
				EXECUTE @RC = [dbo].[ArtikliFPPrepis] @Obj
			ELSE
				EXECUTE @RC = [dbo].[ArtikliFPPrepisKalkMP] @Broj
		END TRY
		BEGIN CATCH

		END CATCH

	END


END
GO

IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[KasaFP_DeletionTrigger]'))
DROP TRIGGER [dbo].[KasaFP_DeletionTrigger]
GO
CREATE TRIGGER [dbo].[KasaFP_DeletionTrigger] 
    ON [dbo].[KasaFP] 
    AFTER DELETE 
AS 
SET NOCOUNT ON 
UPDATE [dbo].[KasaFP_Tombstone] 
    SET [DeletionDate] = GETDATE() 
    FROM deleted 
    WHERE deleted.[Broj] = [dbo].[KasaFP_Tombstone].[Broj] 
IF @@ROWCOUNT = 0 
BEGIN 
    INSERT INTO [dbo].[KasaFP_Tombstone] 
    ([Broj], DeletionDate)
    SELECT [Broj], GETDATE()
    FROM deleted 
END


GO
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[KasaFP_InsertTrigger]'))
DROP TRIGGER [dbo].[KasaFP_InsertTrigger]
GO

CREATE TRIGGER [dbo].[KasaFP_InsertTrigger] 
    ON [dbo].[KasaFP] 
    AFTER INSERT 
AS 
BEGIN 
    SET NOCOUNT ON 
    UPDATE [dbo].[KasaFP] 
    SET [CreationDate] = GETDATE() 
    FROM inserted 
    WHERE inserted.[Broj] = [dbo].[KasaFP].[Broj] 
END;


GO
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[KasaFP_UpdateTrigger]'))
DROP TRIGGER [dbo].[KasaFP_UpdateTrigger]
GO

CREATE TRIGGER [dbo].[KasaFP_UpdateTrigger] 
    ON [dbo].[KasaFP] 
    AFTER UPDATE 
AS 
BEGIN 
    SET NOCOUNT ON 
    UPDATE [dbo].[KasaFP] 
    SET [LastEditDate] = GETDATE() 
    FROM inserted 
    WHERE inserted.[Broj] = [dbo].[KasaFP].[Broj] 
    -- Markiraj u stavkama broj kase, zaključenje i operatera
    -- kad se ažirira polje PoslatNaFP
	IF UPDATE(PoslatNaFP)
	BEGIN
		UPDATE dbo.KasaFPSt SET 
			Kasa = z.Kasa
			, Zakljucenje = z.Zakljucenje 
			, Operater = z.Operater
		FROM inserted z 
		WHERE z.Broj = dbo.KasaFPSt.Broj;    

		BEGIN TRY
			UPDATE dbo.ArtikliFP SET Zalihe = Zalihe - t.kol
			FROM (SELECT Sifra, SUM(Kolicina) kol FROM dbo.KasaFPSt 
					WHERE  Broj IN (SELECT broj FROM INSERTED i) GROUP BY Sifra) t
				WHERE dbo.ArtikliFP.Sifra = t.Sifra
		END TRY
		BEGIN CATCH

		END CATCH
	END
END;


GO

IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[KasaFPSt_DeletionTrigger]'))
DROP TRIGGER [dbo].[KasaFPSt_DeletionTrigger]
GO

CREATE TRIGGER [dbo].[KasaFPSt_DeletionTrigger] 
    ON [dbo].[KasaFPSt] 
    AFTER DELETE 
AS 
SET NOCOUNT ON 
UPDATE [dbo].[KasaFPSt_Tombstone] 
    SET [DeletionDate] = GETDATE() 
    FROM deleted 
    WHERE deleted.[Broj] = [dbo].[KasaFPSt_Tombstone].[Broj] 
    AND deleted.[RedBroj] = [dbo].[KasaFPSt_Tombstone].[RedBroj] 
IF @@ROWCOUNT = 0 
BEGIN 
    INSERT INTO [dbo].[KasaFPSt_Tombstone] 
    ([Broj], [RedBroj], DeletionDate)
    SELECT [Broj], [RedBroj], GETDATE()
    FROM deleted 
END


GO
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[KasaFPSt_InsertTrigger]'))
DROP TRIGGER [dbo].[KasaFPSt_InsertTrigger]
GO

CREATE TRIGGER [dbo].[KasaFPSt_InsertTrigger] 
    ON [dbo].[KasaFPSt] 
    AFTER INSERT 
AS 
BEGIN 
    SET NOCOUNT ON 
    UPDATE [dbo].[KasaFPSt] 
    SET [CreationDate] = GETDATE() 
    FROM inserted 
    WHERE inserted.[Broj] = [dbo].[KasaFPSt].[Broj] 
    AND inserted.[RedBroj] = [dbo].[KasaFPSt].[RedBroj] 
END;


GO
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[KasaFPSt_UpdateTrigger]'))
DROP TRIGGER [dbo].[KasaFPSt_UpdateTrigger]
GO

CREATE TRIGGER [dbo].[KasaFPSt_UpdateTrigger] 
    ON [dbo].[KasaFPSt] 
    AFTER UPDATE 
AS 
BEGIN 
    SET NOCOUNT ON 
    UPDATE [dbo].[KasaFPSt] 
    SET [LastEditDate] = GETDATE() 
    FROM inserted 
    WHERE inserted.[Broj] = [dbo].[KasaFPSt].[Broj] 
    AND inserted.[RedBroj] = [dbo].[KasaFPSt].[RedBroj] 
END;


GO
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[LagerListaMP]'))
DROP VIEW [dbo].[LagerListaMP]
GO

CREATE VIEW dbo.LagerListaMP
AS
SELECT     Stanje.Objekat, Artikli.Sifra, Artikli.Artikal, Artikli.NazivArtikla, Artikli.Barkod, Artikli.SifraKodDobavljaca AS SKU, Artikli.JM, Stanje.Cena, Stanje.Zalihe, 
                      ROUND(Stanje.Cena * Stanje.Zalihe, 2) AS Iznos, Kategorije.Kategorija, Kategorije.Ime AS KategorijaIme, Artikli.ISBN, Artikli.Pisac, Artikli.Izdavac, Artikli.Velicina, 
                      Artikli.Boja, Artikli.Brend, Artikli.ProizvodjacIme, Artikli.Dobavljac, Partneri.NazivFirme AS NazivDobavljaca
FROM         Artikli INNER JOIN
                      Stanje ON Artikli.Sifra = Stanje.Sifra LEFT OUTER JOIN
                      Partneri ON Artikli.Dobavljac = Partneri.Partner LEFT OUTER JOIN
                      Kateg4 AS Kategorije ON Artikli.Kategorija = Kategorije.Kategorija
GO

update Tarife set TarifaA = 'B' Where Tarifa = 'P2' and TarifaA = 'A'
GO
-- novi skript za izmenu KasaA
-- skript za novu verziju sa KasaA pričom

IF (SELECT COUNT(*) br FROM sys.columns c WHERE c.name = 'KasaABroj' AND object_id = OBJECT_ID(N'[dbo].[KasaFP]')) = 0
	ALTER TABLE [dbo].[KasaFP] ADD [KasaABroj] INT NULL
IF (SELECT COUNT(*) br FROM sys.columns c WHERE c.name = 'Kasa' AND object_id = OBJECT_ID(N'[dbo].[Depozit]')) = 0
	ALTER TABLE [dbo].[Depozit] ADD [Kasa] NVARCHAR(3) NULL
GO


SET ANSI_PADDING OFF
GO

-- log za izmenu Artikli i ArtikliFP
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[ArtikliFPLog](
	[Sifra] [int] NOT NULL,
	[Datum] [smalldatetime] NULL,
	[Akcija] [varchar](1) NULL,
 CONSTRAINT [PK_ArtikliFPLog] PRIMARY KEY CLUSTERED 
(
	[Sifra] 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]

GO

ALTER TABLE [dbo].[ArtikliFPLog] ADD  CONSTRAINT [DF_ArtikliFPLog_Datum]  DEFAULT (getdate()) FOR [Datum]
GO
ALTER TABLE [dbo].[ArtikliFPLog] ADD  CONSTRAINT [DF_ArtikliFPLog_Akcija]  DEFAULT ('N') FOR [Akcija]
GO

CREATE TABLE [dbo].[Art3xLog](
	[id] [NVARCHAR](10) NOT NULL,
	[Bar_code] [NVARCHAR](14) NOT NULL,
	[Datum] [smalldatetime] NULL,
	[Akcija] [varchar](1) NULL,
 CONSTRAINT [PK_Art3xLog] PRIMARY KEY CLUSTERED 
(
	[id], [Bar_code] 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]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Art3xLog] ADD  CONSTRAINT [DF_Art3xLog_Datum]  DEFAULT (getdate()) FOR [Datum]
GO

ALTER TABLE [dbo].[Art3xLog] ADD  CONSTRAINT [DF_Art3xLog_Akcija]  DEFAULT ('N') FOR [Akcija]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Dejan Dabic
-- Create date: 2009-04-28
-- Description:	Upis u log svih artikala koji su insertovani ili update-ovani
-- =============================================
CREATE TRIGGER [dbo].[trgArtikliFP_Log] 
   ON  [dbo].[ArtikliFP] 
   FOR INSERT,UPDATE, DELETE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @Akcija AS VARCHAR(1)
	IF (SELECT COUNT(*) BR FROM INSERTED) = 0
		SET @Akcija = 'B'
	IF (SELECT COUNT(*) BR FROM DELETED) = 0
		SET @Akcija = 'N'
	IF (SELECT COUNT(*) BR FROM INSERTED) > 0 AND (SELECT COUNT(*) BR FROM DELETED) > 0
		SET @Akcija = 'M'
	
		
	UPDATE [tbl] SET tbl.Akcija = @Akcija, tbl.Datum = GETDATE() 
		from ArtikliFPLog [tbl] JOIN DELETED d ON tbl.Sifra = d.Sifra ;
	insert into ArtikliFPLog (Sifra, Akcija) 
		Select Sifra, @Akcija from Inserted i 
			Where not i.Sifra in (Select Sifra from ArtikliFPLog)
END

GO

CREATE TRIGGER dbo.ArtikliUpdateFP
	ON dbo.Artikli
	FOR UPDATE
AS
BEGIN
-- update artikala za fiskalni štampač u tabelu ArtikliFP
	IF UPDATE(NazivArtikla) OR UPDATE(JM) OR UPDATE(Barkod) OR UPDATE(PLU) OR UPDATE(Tip) OR UPDATE(Kategorija)
		BEGIN
		Update [a] 
			set a.[NazivArtikla] = LEFT(i.[NazivArtikla],50)
				, a.[JM] = i.[JM]
				, a.[Kategorija] = i.[Kategorija]
				, a.[Barkod] = i.[Barkod]
				, a.[PluVaga] = i.[Plu]
				, a.[Tip] = i.[Tip]
			FROM [dbo].[ArtikliFP] [a] JOIN inserted i 
			ON a.Sifra = i.Sifra;
		END
END
GO
-- =============================================
-- Author:		Dejan
-- Create date: 3.10.2010
-- Description:	Triger za praćenje promena na Art3x
-- =============================================
CREATE TRIGGER dbo.trgArt3x_Log 
   ON  dbo.Art3x 
   FOR INSERT,DELETE,UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
	SET NOCOUNT ON;
	DECLARE @Akcija AS VARCHAR(1)
	IF (SELECT COUNT(*) BR FROM INSERTED) = 0
		SET @Akcija = 'B'
	IF (SELECT COUNT(*) BR FROM DELETED) = 0
		SET @Akcija = 'N'
	IF (SELECT COUNT(*) BR FROM INSERTED) > 0 AND (SELECT COUNT(*) BR FROM DELETED) > 0
		SET @Akcija = 'M'
	
		
	UPDATE [tbl] SET tbl.Akcija = @Akcija, tbl.Datum = GETDATE() 
		from Art3xLog [tbl] JOIN DELETED d ON tbl.id = d.id AND tbl.bar_code = d.bar_code ;
	insert into dbo.Art3xLog (ID, Bar_code, Akcija) 
		Select ID, Bar_code, @Akcija from Inserted i 
		Where NOT EXISTS 
			(SELECT ID, Bar_code FROM dbo.Art3xLog l 
			WHERE i.id = l.id AND i.Bar_code = l.Bar_code)
END
GO

-- sredi tabelu zaKasuPOS
if exists (select * from sysobjects where id = object_id('dbo.zaKasuPOS') and sysstat & 0xf = 3)
	drop table dbo.zaKasuPOS;

CREATE TABLE dbo.zaKasuPOS (
	Objekat nvarchar (6) COLLATE Slovenian_CI_AS NOT NULL ,
	Sifra INT NOT NULL,
	ID varchar (10) COLLATE Slovenian_CI_AS NOT NULL ,
	PluFP INT,
	Bar_cod varchar (13) COLLATE Slovenian_CI_AS NULL ,
	PLU_Naziv nvarchar (50) COLLATE Slovenian_CI_AS NULL ,
	Cena NUMERIC(12,2) NULL CONSTRAINT DF_zaKasuPOS_Cena DEFAULT (0),
	Tarifa varchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF_zaKasuPOS_Tarifa DEFAULT ('A'),
	Ind_deckol varchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF_zaKasuPOS_Ind_dec DEFAULT ('N'),
	Ind_otv varchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF_zaKasuPOS_Ind_o DEFAULT ('N'),
	Unos_l varchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF_zaKasuPOS_Unos DEFAULT ('N'),
	CONSTRAINT zaKasuPOS_PK PRIMARY KEY  NONCLUSTERED 
	(
		Objekat,
		Sifra
	) WITH  FILLFACTOR = 90
);
GO

-- promeni strukturu arhive za pos
DECLARE @postojiArh AS BIT
SET @postojiArh = 0;

if exists (select * from sysobjects where id = object_id('dbo.ArhivaZaPos') and sysstat & 0xf = 3)
BEGIN
	SELECT * INTO tmpTbl FROM dbo.ArhivaZaPos
	SET @postojiArh = 1;
	drop table dbo.ArhivaZaPos;
END

CREATE TABLE dbo.ArhivaZaPos (
	Objekat varchar (6) COLLATE Slovenian_CI_AS NOT NULL ,
	Sifra INT NOT NULL,
	ID varchar (10) COLLATE Slovenian_CI_AS NOT NULL ,
	PluFP INT,
	Bar_cod varchar (13) COLLATE Slovenian_CI_AS NULL ,
	PLU_Naziv nvarchar (50) COLLATE Slovenian_CI_AS NULL ,
	Cena NUMERIC(12,2) NULL CONSTRAINT DF_ArhivaZaPos_Cena DEFAULT (0),
	Tarifa varchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF_ArhivaZaPos_Tarifa DEFAULT ('A'),
	Ind_deckol varchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF_ArhivaZaPos_Ind_dec DEFAULT ('N'),
	Ind_otv varchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF_ArhivaZaPos_Ind_o DEFAULT ('N'),
	[Ind_bottle] [varchar](1) NULL,
	[Kau_id] [varchar](10) NULL,
	Unos_l varchar (1) COLLATE Slovenian_CI_AS NULL CONSTRAINT DF_ArhivaZaPos_Unos DEFAULT ('N'),
	CONSTRAINT PK_ArhivaZaPos PRIMARY KEY CLUSTERED 
	(
		Objekat,
		Sifra
	) WITH  FILLFACTOR = 90
);
GO

if exists (select * from sysobjects where id = object_id('tmpTbl') and sysstat & 0xf = 3)
BEGIN
	INSERT INTO dbo.ArhivaZaPos
	        ( Objekat ,
	          Sifra,
	          ID ,
	          Bar_cod ,
	          PLU_Naziv ,
	          Cena ,
	          Tarifa ,
	          Ind_deckol ,
	          Ind_otv ,
	          Ind_bottle ,
	          Kau_id ,
	          Unos_l
	        )
	SELECT Objekat ,
	          CAST(ID AS INT) Sifra,
	          ID ,
	          Bar_cod ,
	          PLU_Naziv ,
	          Cena ,
	          Tarifa ,
	          Ind_deckol ,
	          Ind_otv ,
	          Ind_bottle ,
	          Kau_id ,
	          Unos_l
	FROM tmpTbl
	DROP TABLE tmpTbl
END
UPDATE dbo.ArhivaZaPos SET PLU_Naziv = LEFT(a.NazivArtikla, 50), PluFP = a.PluFP
	FROM dbo.Artikli a WHERE dbo.ArhivaZaPos.Sifra = a.Sifra
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[bof_PrepisPopisauBT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[bof_PrepisPopisauBT]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[bof_PrepisPrijemnica]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[bof_PrepisPrijemnica]
GO
-- tabela KasaA i KasaASt
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KasaA]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[KasaA](
		[Broj] [int] IDENTITY(1,1) NOT NULL,
		[Dokument] [varchar](10) NULL,
		[Datum] [datetime] NULL,
		[Iznos] [numeric](10, 2) NULL,
		[IznosPDV] [numeric](10, 2) NULL,
		[Placanje] [int] NULL,
		[Promena] [int] NULL,
		[Partner] [nvarchar](8) NULL,
		[Valuta] [datetime] NULL,
		[Protokol] [int] NULL,
		[Knjizeno] [bit] NULL,
		[ok] [bit] NULL,
		[Operater] [smallint] NULL,
		[Objekat] [varchar](3) NULL,
		[Kasa] [varchar](3) NOT NULL,
		[Zakljucenje] [smallint] NULL,
		[SysDatum] [datetime] NULL,
		[Iznos2] [numeric](10, 2) NULL,
		[Gotovina] [numeric](10, 2) NULL,
		[Kartica] [numeric](10, 2) NULL,
		[Racun] [numeric](10, 2) NULL,
		[Kredit] [numeric](10, 2) NULL,
		[Opis] [nvarchar](60) NULL,
		[Faktura] [varchar](15) NULL,
		[ExterniBroj] [int] NULL,
		[ExterniPromena] [smallint] NULL,
		[KasaABroj] INT NULL,
		[CardID] [smallint] NULL,
		[PoslatNaFP] [bit] NULL,
		[ZakljucenDan] [bit] NULL,
		[LastEditDate] [datetime] NULL,
		[CreationDate] [datetime] NULL,
		[BrojKartice] [varchar](20) NULL,
		[PosTerminal] [smallint] NULL,
		[Zamena] [bit] NULL,
		[Povrat] [bit] NULL,
		[BrojRata] [smallint] NULL,
		[PopustNaRacun] [numeric](10, 2) NULL,
		[PartnerPopust] [varchar](8) NULL,
		[Stornirano] [bit] NULL,
		[Poslato] [bit] NULL,
		[ValidacijaID] [int] NULL,
	 CONSTRAINT [PK_KasaA_1] PRIMARY KEY CLUSTERED 
	(
		[Broj] ASC,
		[Kasa] 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

SET ANSI_PADDING OFF
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO
IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KasaASt]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[KasaASt](
		[Broj] [int] NOT NULL,
		[RedBroj] [int] IDENTITY(1,1) NOT NULL,
		[Sifra] [int] NOT NULL,
		[Kolicina] [numeric](8, 3) NULL,
		[Cena] [numeric](8, 2) NULL,
		[Rabat] [numeric](5, 2) NULL,
		[TarifaA] [varchar](1) NULL,
		[Stopa] [numeric](4, 1) NULL,
		[Operater] [int] NULL,
		[Storno] [bit] NULL,
		[Kasa] [varchar](3) NOT NULL,
		[Zakljucenje] [smallint] NULL,
		[LastEditDate] [datetime] NULL,
		[CreationDate] [datetime] NULL,
	 CONSTRAINT [PK_KasaASt_1] PRIMARY KEY CLUSTERED 
	(
		[Broj] ASC,
		[RedBroj] ASC,
		[Kasa] 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

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Iznos]  DEFAULT ((0)) FOR [Iznos]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_IznosPDV]  DEFAULT ((0)) FOR [IznosPDV]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Placanje]  DEFAULT ((1)) FOR [Placanje]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Promena]  DEFAULT ((211)) FOR [Promena]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Knjizeno]  DEFAULT ((0)) FOR [Knjizeno]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_ok]  DEFAULT ((0)) FOR [ok]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Operater]  DEFAULT ((0)) FOR [Operater]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Objekat]  DEFAULT ('1') FOR [Objekat]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Zakljuce]  DEFAULT ((0)) FOR [Zakljucenje]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_SysDatum]  DEFAULT (getdate()) FOR [SysDatum]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Iznos2]  DEFAULT ((0)) FOR [Iznos2]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Gotovina]  DEFAULT ((0)) FOR [Gotovina]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Kartica]  DEFAULT ((0)) FOR [Kartica]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Racun]  DEFAULT ((0)) FOR [Racun]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Kredit]  DEFAULT ((0)) FOR [Kredit]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_PoslatNaFP]  DEFAULT ((0)) FOR [PoslatNaFP]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_ZakljucenDan]  DEFAULT ((0)) FOR [ZakljucenDan]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_LastEditDate]  DEFAULT (getdate()) FOR [LastEditDate]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_CreationDate]  DEFAULT (getdate()) FOR [CreationDate]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Zamena]  DEFAULT ((0)) FOR [Zamena]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_BrojRata]  DEFAULT ((0)) FOR [BrojRata]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_PopustNaRacun]  DEFAULT ((0)) FOR [PopustNaRacun]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Stornirano]  DEFAULT ((0)) FOR [Stornirano]
GO

ALTER TABLE [dbo].[KasaA] ADD  CONSTRAINT [DF_KasaA_Poslato]  DEFAULT ((0)) FOR [Poslato]
GO

ALTER TABLE [dbo].[KasaASt]  WITH CHECK ADD  CONSTRAINT [FK_KasaASt_KasaA] FOREIGN KEY([Broj], [Kasa])
REFERENCES [dbo].[KasaA] ([Broj], [Kasa])
ON UPDATE CASCADE
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[KasaASt] CHECK CONSTRAINT [FK_KasaASt_KasaA]
GO

ALTER TABLE [dbo].[KasaASt] ADD  CONSTRAINT [DF_KasaASt_Kolicina]  DEFAULT ((0)) FOR [Kolicina]
GO

ALTER TABLE [dbo].[KasaASt] ADD  CONSTRAINT [DF_KasaASt_Cena]  DEFAULT ((0)) FOR [Cena]
GO

ALTER TABLE [dbo].[KasaASt] ADD  CONSTRAINT [DF_KasaASt_Rabat]  DEFAULT ((0)) FOR [Rabat]
GO

ALTER TABLE [dbo].[KasaASt] ADD  CONSTRAINT [DF_KasaASt_Tarifa]  DEFAULT ('A') FOR [TarifaA]
GO

ALTER TABLE [dbo].[KasaASt] ADD  CONSTRAINT [DF_KasaASt_Stopa]  DEFAULT ((17)) FOR [Stopa]
GO

ALTER TABLE [dbo].[KasaASt] ADD  CONSTRAINT [DF_KasaASt_Operater]  DEFAULT ((0)) FOR [Operater]
GO

ALTER TABLE [dbo].[KasaASt] ADD  CONSTRAINT [DF_KasaASt_Storno]  DEFAULT ((0)) FOR [Storno]
GO

ALTER TABLE [dbo].[KasaASt] ADD  CONSTRAINT [DF_KasaASt_Zakljucenje]  DEFAULT ((0)) FOR [Zakljucenje]
GO

ALTER TABLE [dbo].[KasaASt] ADD  CONSTRAINT [DF_KasaASt_LastEditDate]  DEFAULT (getdate()) FOR [LastEditDate]
GO

ALTER TABLE [dbo].[KasaASt] ADD  CONSTRAINT [DF_KasaASt_CreationDate]  DEFAULT (getdate()) FOR [CreationDate]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KasaAPrepis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[KasaAPrepis]
GO


CREATE PROCEDURE [dbo].[KasaAPrepis]
	@Broj INT
AS
	SET NOCOUNT ON ;
	DECLARE @BrojNovi INT
	DECLARE @Kasa VARCHAR(3) 
	SET @Kasa = ( SELECT   Kasa
			   FROM     dbo.KasaA
			   WHERE    Broj = @Broj
			 )
	IF	@Kasa IS NULL
		RETURN;
	SET @BrojNovi = ( SELECT   MAX(Broj) br
				   FROM     dbo.KasaFP
				   WHERE    Kasa = @Kasa
				 )
	SET @BrojNovi = ISNULL(@BrojNovi, 0) + 1
	IF	@BrojNovi = 1
		SET @BrojNovi = CONVERT(int, @Kasa + '000001')
	INSERT INTO dbo.KasaFP
		( Broj ,
		  Dokument ,
		  Datum ,
		  Iznos ,
		  IznosPDV ,
		  Placanje ,
		  Promena ,
		  Partner ,
		  Valuta ,
		  Protokol ,
		  Knjizeno ,
		  ok ,
		  Operater ,
		  Objekat ,
		  Kasa ,
		  Zakljucenje ,
		  SysDatum ,
		  Iznos2 ,
		  Gotovina ,
		  Kartica ,
		  Racun ,
		  Kredit ,
		  Opis ,
		  Faktura ,
		  ExterniBroj ,
		  ExterniPromena ,
		  KasaABroj,
		  CardID ,
		  PoslatNaFP ,
		  ZakljucenDan ,
		  LastEditDate ,
		  CreationDate ,
		  BrojKartice ,
		  PosTerminal ,
		  Zamena ,
		  Povrat ,
		  BrojRata ,
		  PopustNaRacun ,
		  PartnerPopust ,
		  Stornirano ,
		  Poslato ,
		  ValidacijaID
		        
		)
		SELECT  @BrojNovi broj ,
				Dokument ,
				Datum ,
				Iznos ,
				IznosPDV ,
				Placanje ,
				Promena ,
				Partner ,
				Valuta ,
				Protokol ,
				Knjizeno ,
				ok ,
				Operater ,
				Objekat ,
				Kasa ,
				Zakljucenje ,
				SysDatum ,
				Iznos2 ,
				Gotovina ,
				Kartica ,
				Racun ,
				Kredit ,
				Opis ,
				Faktura ,
				ExterniBroj ,
				ExterniPromena ,
				@Broj KasaABroj,
				CardID ,
				PoslatNaFP ,
				ZakljucenDan ,
				LastEditDate ,
				CreationDate ,
				BrojKartice ,
				PosTerminal ,
				Zamena ,
				Povrat ,
				BrojRata ,
				PopustNaRacun ,
				PartnerPopust ,
				Stornirano ,
				Poslato ,
				ValidacijaID
		FROM    dbo.KasaA a
		WHERE   a.Broj = @Broj
	DECLARE @tbl AS TABLE
	(
	  Broj INT ,
	  RedBroj INT ,
	  BrojI INT IDENTITY(1, 1)
	)
	INSERT INTO @tbl
		( Broj ,
		  RedBroj 
		)
		SELECT  Broj ,
				RedBroj
		FROM    dbo.KasaASt
	INSERT INTO dbo.KasaFPSt
		( Broj ,
		  RedBroj ,
		  Sifra ,
		  Kolicina ,
		  Cena ,
		  Rabat ,
		  TarifaA ,
		  Stopa ,
		  Operater ,
		  Storno ,
		  Kasa ,
		  Zakljucenje ,
		  LastEditDate ,
		  CreationDate
		        
		)
		SELECT  @BrojNovi Broj ,
				t.BrojI RedBroj ,
				Sifra ,
				Kolicina ,
				Cena ,
				Rabat ,
				TarifaA ,
				Stopa ,
				Operater ,
				Storno ,
				Kasa ,
				Zakljucenje ,
				LastEditDate ,
				CreationDate
		FROM    dbo.KasaASt st
				INNER JOIN @tbl t ON st.Broj = t.Broj
									 AND st.RedBroj = t.RedBroj
--ažuriraj zaključenje i zalihe
		UPDATE dbo.KasaFPSt SET 
			Kasa = z.Kasa
			, Zakljucenje = z.Zakljucenje 
			, Operater = z.Operater
		FROM dbo.KasaFP z 
		WHERE z.Broj = dbo.KasaFPSt.Broj AND z.Broj = @BrojNovi;    

		BEGIN TRY
			UPDATE dbo.ArtikliFP SET Zalihe = Zalihe - t.kol
			FROM (SELECT Sifra, SUM(Kolicina) kol FROM dbo.KasaFPSt 
					WHERE  Broj IN (SELECT broj FROM dbo.KasaFPSt i WHERE i.Broj = @BrojNovi) GROUP BY Sifra) t
				WHERE dbo.ArtikliFP.Sifra = t.Sifra
		END TRY
		BEGIN CATCH

		END CATCH
		DELETE FROM dbo.KasaASt WHERE Broj = @Broj
		DELETE FROM dbo.KasaA WHERE Broj = @Broj

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Dejan
-- Create date: 19.9.2010
-- Description:	Update triger koji prepisuje račun u KasaFP
-- =============================================
CREATE TRIGGER [dbo].[KasaA_UpdateTrigger] 
   ON  [dbo].[KasaA] 
   AFTER UPDATE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    IF UPDATE(PoslatNaFP)
    BEGIN
		DECLARE @Broj INT
		DECLARE @PoslatNaFp BIT
		
		SELECT TOP 1 @Broj = Broj, @PoslatNaFp = PoslatNaFP FROM INSERTED
		IF @PoslatNaFp <> 0
			EXEC dbo.KasaAPrepis @Broj
    END

END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pos_UpisUArhivazaPos]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pos_UpisUArhivazaPos]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pos_UpisUDnevnik]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pos_UpisUDnevnik]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pos_UpisUArhivazaPos]
AS
UPDATE ArhivazaPOS Set ArhivazaPOS.Unos_l = zaKasuPos.Unos_l
	, ArhivazaPOS.Cena = zaKasuPos.Cena
	, ArhivazaPOS.Tarifa = zaKasuPos.Tarifa
	, ArhivazaPOS.Bar_cod = zaKasuPos.Bar_cod
	, ArhivazaPOS.PLU_Naziv = zaKasuPos.PLU_Naziv
	, ArhivazaPOS.ind_deckol = zaKasuPos.ind_deckol
	, ArhivazaPOS.ind_otv = zaKasuPos.ind_otv
 	from zaKasuPos 
	where ArhivazaPOS.[Sifra] = zaKasuPos.[Sifra] and ArhivazaPOS.Objekat = zaKasuPos.Objekat and zaKasuPos.Unos_l <> N'0'

Insert Into ArhivaZaPos (Objekat, Sifra, [ID], PluFP, Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
select Objekat, Sifra, [ID], PluFP, Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv from zaKasuPos
	where not exists (select Objekat, [Sifra] from ArhivaZaPos ar 
		where Objekat = zaKasuPos.Objekat and [Sifra] = zaKasuPos.[Sifra])



GO

/****** Object:  StoredProcedure [dbo].[pos_UpisUDnevnik]    Script Date: 09/26/2010 23:35:19 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pos_UpisUDnevnik]
	@Broj INT = 0, @Promena INT = 0
AS
-- prepis u dnevnik svega što se prenosi
SET NOCOUNT ON;


DECLARE @MaxID AS INTEGER
Select @MaxID = Max(IDPos) from dbo.ArhivaZaPOSDnevnik
IF ISNULL(@MaxID,0) = 0
	SET @MaxID = 1;
set @MaxID = @MaxID + 1
-- u dnevniku pamti samo zadnji mesec
Delete from dbo.ArhivaZaPOSDnevnik Where Datum < getdate() - 60
INSERT INTO dbo.ArhivaZaPOSDnevnik
        ( IDPos ,
          Datum ,
          Sifra ,
          Unos_L ,
          [Broj] ,
          [Promena] ,  
          StCena ,
          Cena
        )
select @MaxID AS IDPos
	, GETDATE() AS datum
	, za.Sifra
	, za.Unos_l
	, @Broj AS broj
	, @Promena AS promena
	, ISNULL(ArhivazaPOS.Cena, 0) as StCena 
	, za.Cena
from zaKasuPos za left join ArhivazaPOS on za.Sifra = ArhivazaPOS.Sifra
	AND za.Objekat = ArhivazaPOS.Objekat
	WHERE za.Unos_l <> '0'
RETURN 0;

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliFPPrepisPopis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ArtikliFPPrepisPopis]
GO

/****** Object:  StoredProcedure [dbo].[ArtikliFPPrepis]    Script Date: 09/26/2010 23:36:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliFPPrepis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ArtikliFPPrepis]
GO

/****** Object:  StoredProcedure [dbo].[ArtikliFPPrepisNivelMP]    Script Date: 09/26/2010 23:36:53 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliFPPrepisNivelMP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ArtikliFPPrepisNivelMP]
GO

/****** Object:  StoredProcedure [dbo].[ArtikliFPPrepisKalkMP]    Script Date: 09/26/2010 23:36:54 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArtikliFPPrepisKalkMP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ArtikliFPPrepisKalkMP]
GO

/****** Object:  StoredProcedure [dbo].[KasaAPrepis]    Script Date: 09/26/2010 23:36:54 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KasaAPrepis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[KasaAPrepis]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE procedure [dbo].[ArtikliFPPrepisPopis]
	@Broj as INT
AS

DECLARE @Obj AS NVARCHAR(6)
DECLARE @Objekat AS NVARCHAR(6)
DECLARE @Promena AS INT

SELECT @Obj = Objekat, @Promena = Promena FROM dbo.Popis0 WHERE Broj = @Broj
IF @Obj IS NULL 
	RETURN;
SET @Objekat = @Obj
BEGIN TRAN
BEGIN TRY
	-- prvo ubaci nove artikle
	insert into ArtikliFP 
		(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija, PluVaga)
	select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija, a.PLU 
	from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
	inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
	WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra)
		AND a.Sifra IN (SELECT Sifra FROM dbo.Popis WHERE Broj = @Broj);

	-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
	Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
		from ArtikliFP afp inner join 
		(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
		where afp.Cena <> Round(s.CenaS,2)

	-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
	Update afp set afp.Zalihe = s.Zalihe
		from ArtikliFP afp inner join 
		(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
		where afp.Zalihe <> s.Zalihe
	-- azuriraj nazive ako su menjani
	Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
		from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
		where afp.NazivArtikla <> a.NazivArtikla
	-- tarife poreza
	Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
		from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
		inner join Tarife T on a.Tarifa = T.Tarifa
		where afp.Tarifa <> T.TarifaA


	-- azuriraj barkod ili jedinicu mere
	Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm, afp.PluVaga = a.PLU
		from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
		where afp.Barkod <> a.Barkod or afp.jm <> a.jm OR afp.PluVaga <> a.PLU
	-- azuriraj slobodnu cenu ako je markiran
	Update afp set afp.SlobodnaCena = a.SlobodnaCena
		from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
		where afp.Marker <> 0;

	TRUNCATE TABLE dbo.zaKasuPOS;
	SELECT DISTINCT Sifra, (select TOP 1 Cena FROM dbo.Popis K WHERE K.Broj = kst.Broj AND k.Sifra = kst.Sifra) AS ProdCena 
	INTO #Cene
	FROM dbo.Popis kst WHERE Broj = @Broj

	insert into dbo.ZaKasuPos (Objekat, Sifra, [ID], PluFP, Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
	select @Obj as Objekat, a.Sifra, CONVERT(VARCHAR(10), a.Sifra), a.PLU, a.Barkod, 
		Left(a.NazivArtikla, 50) as nn, c.ProdCena, 
		a.Tarifa , 
		'N' as Unos_l, 
		ind_deckol = case when a.Decimale = 0 THEN 'N' WHEN a.Decimale <> 0 THEN 'D' END, 
		ind_otv = case when a.SlobodnaCena = 0 THEN 'N' WHEN a.SlobodnaCena <> 0 THEN 'D' END 
	From ArtikliFP a Inner Join #Cene c On a.Sifra = c.Sifra

	DROP TABLE #Cene
	UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'P' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena <> ArhivazaPOS.Cena
	UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'C' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod <> ArhivazaPOS.Bar_cod) OR (zaKasuPos.PLU_naziv <> ArhivazaPOS.PLU_naziv)  OR (zaKasuPos.Tarifa <> ArhivazaPOS.Tarifa)) 
	UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND (zaKasuPos.Bar_cod = ArhivazaPOS.Bar_cod) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv) 
	UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod is null) and (ArhivazaPOS.Bar_cod is null)) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv)

	-- prepis u ArhivaZaPosDnevnik
	EXEC dbo.pos_UpisUDnevnik @Broj, @Promena
	EXEC dbo.pos_UpisUArhivazaPos
	COMMIT TRAN
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	RAISERROR ('Dokument nije pravilno poslat na POS sistem', 2, 1) 
	RETURN -1;
END CATCH
RETURN	

GO

/****** Object:  StoredProcedure [dbo].[ArtikliFPPrepis]    Script Date: 09/26/2010 23:36:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE procedure [dbo].[ArtikliFPPrepis]
	@Obj as nvarchar(6) = '1'
AS
SET NOCOUNT ON;

-- prvo ubaci nove artikle
insert into ArtikliFP 
	(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija, PluVaga)
select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija, a.PLU 
from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra);

-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Cena <> Round(s.CenaS,2)

-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
Update afp set afp.Zalihe = s.Zalihe
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Zalihe <> s.Zalihe

-- azuriraj nazive ako su menjani
Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.NazivArtikla <> a.NazivArtikla


-- tarife poreza
Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	inner join Tarife T on a.Tarifa = T.Tarifa
	where afp.Tarifa <> T.TarifaA

-- azuriraj slobodnu cenu ako je markiran
Update afp set afp.SlobodnaCena = a.SlobodnaCena
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Marker <> 0 AND afp.Cena <> 0;

-- azuriraj barkod ili jedinicu mere
Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm, afp.PluVaga = a.Plu
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Barkod <> a.Barkod or afp.jm <> a.jm OR afp.PluVaga <> a.PLU

-- upis u zaKasaPos svih izmena
TRUNCATE TABLE dbo.zaKasuPOS;
INSERT INTO dbo.zaKasuPOS
        ( Objekat ,
			Sifra,
          ID ,
          PluFP,
          Bar_cod ,
          PLU_Naziv ,
          Cena ,
          Tarifa ,
          Ind_deckol ,
          Ind_otv ,
          Unos_l
        )
SELECT @Obj AS objekat
	, a.Sifra
	, CONVERT(VARCHAR(10), a.Sifra) ID
	, a.Plu
	, a.Barkod
	, LEFT(a.NazivArtikla, 50)
	, Round(a.Cena,2) Cena
	, a.Tarifa
	, CASE WHEN a.Decimale <> 0 THEN 'D' ELSE 'N' END 
	, CASE WHEN a.SlobodnaCena <> 0 THEN 'D' ELSE 'N' END 
	, 'N' Unos_L
from ArtikliFP a
WHERE NOT a.Sifra IN (SELECT Sifra FROM dbo.ArhivaZaPos arh WHERE arh.Objekat = @Obj)
AND a.Cena <> 0

INSERT INTO dbo.zaKasuPOS
        ( Objekat ,
			Sifra,
          ID ,
          PluFP,
          Bar_cod ,
          PLU_Naziv ,
          Cena ,
          Tarifa ,
          Ind_deckol ,
          Ind_otv ,
          Unos_l
        )
SELECT @Obj AS objekat
	, a.Sifra
	, CONVERT(VARCHAR(10), a.Sifra) ID
	, a.Plu
	, a.Barkod
	, LEFT(a.NazivArtikla, 50)
	, Round(a.Cena,2) Cena
	, a.Tarifa
	, CASE WHEN a.Decimale <> 0 THEN 'D' ELSE 'N' END 
	, CASE WHEN a.SlobodnaCena <> 0 THEN 'D' ELSE 'N' END 
	, a.Unos_L
from ArtikliFP a
INNER join (SELECT Sifra, PLU_Naziv, Cena, Bar_cod, Tarifa FROM dbo.ArhivaZaPos WHERE Objekat = @Obj) s on a.Sifra = s.Sifra
WHERE ( LEFT(a.NazivArtikla, 50) <> s.PLU_Naziv OR 
	a.Cena <> s.Cena
	OR a.Barkod <> s.Bar_cod)
	OR a.Tarifa <> s.Tarifa
EXEC dbo.pos_UpisUDnevnik @Broj = 0, @Promena = 0
EXEC dbo.pos_UpisUArhivazaPos

GO

/****** Object:  StoredProcedure [dbo].[ArtikliFPPrepisNivelMP]    Script Date: 09/26/2010 23:36:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE procedure [dbo].[ArtikliFPPrepisNivelMP]
	@Broj as INT
AS

DECLARE @Obj AS NVARCHAR(6)
DECLARE @Objekat AS NVARCHAR(6)
DECLARE @Promena AS INT

SELECT @Obj = Objekat, @Promena = Promena FROM NivelMP0 WHERE Broj = @Broj
IF @Obj IS NULL 
	RETURN;
SET @Objekat = @Obj
-- prvo ubaci nove artikle
insert into ArtikliFP 
	(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija, PluVaga)
select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija, a.PLU
from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra)
	AND a.Sifra IN (SELECT Sifra FROM NivelMP WHERE Broj = @Broj);

-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Cena <> Round(s.CenaS,2)

-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
Update afp set afp.Zalihe = s.Zalihe
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Zalihe <> s.Zalihe
-- azuriraj nazive ako su menjani
Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.NazivArtikla <> a.NazivArtikla
-- tarife poreza
Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	inner join Tarife T on a.Tarifa = T.Tarifa
	where afp.Tarifa <> T.TarifaA


-- azuriraj barkod ili jedinicu mere
Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm, afp.PluVaga = a.PLU
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Barkod <> a.Barkod or afp.jm <> a.jm OR afp.PluVaga <> a.PLU

TRUNCATE TABLE dbo.zaKasuPOS;

SELECT DISTINCT Sifra, (select TOP 1 Cena FROM dbo.NivelMP K WHERE K.Broj = kst.Broj AND k.Sifra = kst.Sifra) AS ProdCena 
INTO #Cene
FROM dbo.NivelMP kst WHERE Broj = @Broj


insert into dbo.ZaKasuPos (Objekat, Sifra, [ID], PluFP, Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
select @Obj as Objekat, a.Sifra, CONVERT(VARCHAR(10), a.Sifra), a.Plu, a.Barkod, 
	Left(a.NazivArtikla, 50) as nn, c.ProdCena, 
	a.Tarifa , 
	'N' as Unos_l, 
	ind_deckol = case when a.Decimale = 0 THEN 'N' WHEN a.Decimale <> 0 THEN 'D' END, 
	ind_otv = case when a.SlobodnaCena = 0 THEN 'N' WHEN a.SlobodnaCena <> 0 THEN 'D' END 
From ArtikliFP a Inner Join #Cene c On a.Sifra = c.Sifra

DROP TABLE #Cene

UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'P' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena <> ArhivazaPOS.Cena
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'C' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod <> ArhivazaPOS.Bar_cod) OR (zaKasuPos.PLU_naziv <> ArhivazaPOS.PLU_naziv)  OR (zaKasuPos.Tarifa <> ArhivazaPOS.Tarifa)) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND (zaKasuPos.Bar_cod = ArhivazaPOS.Bar_cod) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod is null) and (ArhivazaPOS.Bar_cod is null)) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv)

EXEC dbo.pos_UpisUDnevnik @Broj, @Promena

EXEC dbo.pos_UpisUArhivazaPos

GO

/****** Object:  StoredProcedure [dbo].[ArtikliFPPrepisKalkMP]    Script Date: 09/26/2010 23:36:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE procedure [dbo].[ArtikliFPPrepisKalkMP]
	@Broj as INT
AS

DECLARE @Obj AS NVARCHAR(6)
DECLARE @Objekat AS NVARCHAR(6)
DECLARE @Promena AS INT
SELECT @Obj = Objekat, @Promena = Promena FROM KalkMP0 WHERE Broj = @Broj
IF @Obj IS NULL 
	RETURN;
SET @Objekat = @Obj
-- prvo ubaci nove artikle
insert into ArtikliFP 
	(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija, PluVaga, Tip)
select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija, a.PLU, a.Tip 
from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra)
	AND a.Sifra IN (SELECT Sifra FROM KalkMP WHERE Broj = @Broj);

-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Cena <> Round(s.CenaS,2)

-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
Update afp set afp.Zalihe = s.Zalihe
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Zalihe <> s.Zalihe
-- azuriraj nazive ako su menjani
Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.NazivArtikla <> a.NazivArtikla
-- tarife poreza
Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	inner join Tarife T on a.Tarifa = T.Tarifa
	where afp.Tarifa <> T.TarifaA


-- azuriraj barkod ili jedinicu mere
Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm, afp.PluVaga = a.PLU, afp.Tip = a.Tip
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Barkod <> a.Barkod or afp.jm <> a.jm OR afp.PluVaga <> a.PLU OR afp.Tip <> a.Tip

-- azuriraj slobodnu cenu ako je markiran
Update afp set afp.SlobodnaCena = a.SlobodnaCena
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Marker <> 0;

-- Prepis u Arhivu za Pos i Dnevnik
TRUNCATE TABLE dbo.zaKasuPOS;
SELECT DISTINCT Sifra, (select TOP 1 PrCenaKom FROM dbo.KalkMp K WHERE k.Broj = kst.Broj AND k.Sifra = kst.Sifra) AS ProdCena 
INTO #Cene
FROM dbo.KalkMp kst WHERE Broj = @Broj

insert into dbo.ZaKasuPos (Objekat, Sifra, [ID], PluFP, Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
select @Obj as Objekat, a.Sifra, CONVERT(VARCHAR(10), a.Sifra), a.Plu, a.Barkod, 
	Left(a.NazivArtikla, 50) as nn, c.ProdCena, 
	a.Tarifa , 
	'N' as Unos_l, 
	ind_deckol = case when a.Decimale = 0 THEN 'N' WHEN a.Decimale <> 0 THEN 'D' END, 
	ind_otv = case when a.SlobodnaCena = 0 THEN 'N' WHEN a.SlobodnaCena <> 0 THEN 'D' END 
From ArtikliFP a Inner Join #Cene c On a.Sifra = c.Sifra

DROP TABLE #Cene

UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'P' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena <> ArhivazaPOS.Cena
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'C' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod <> ArhivazaPOS.Bar_cod) OR (zaKasuPos.PLU_naziv <> ArhivazaPOS.PLU_naziv)  OR (zaKasuPos.Tarifa <> ArhivazaPOS.Tarifa)) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND (zaKasuPos.Bar_cod = ArhivazaPOS.Bar_cod) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod is null) and (ArhivazaPOS.Bar_cod is null)) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv)

-- prepis u ArhivaZaPosDnevnik
EXEC dbo.pos_UpisUDnevnik @Broj, @Promena

UPDATE ArhivazaPOS Set ArhivazaPOS.Unos_l = zaKasuPos.Unos_l
	, ArhivazaPOS.Cena = zaKasuPos.Cena
	, ArhivazaPOS.Tarifa = zaKasuPos.Tarifa
	, ArhivazaPOS.Bar_cod = zaKasuPos.Bar_cod
	, ArhivazaPOS.PLU_Naziv = zaKasuPos.PLU_Naziv
	, ArhivaZaPos.PluFP = zaKasuPOS.PluFP
	, ArhivazaPOS.ind_deckol = zaKasuPos.ind_deckol
	, ArhivazaPOS.ind_otv = zaKasuPos.ind_otv
 	from zaKasuPos 
	where ArhivazaPOS.Objekat = zaKasuPos.Objekat AND ArhivazaPOS.[Sifra] = zaKasuPos.[Sifra]
	and zaKasuPos.Unos_l <> '0'

Insert Into dbo.ArhivaZaPos (Objekat, Sifra, [ID], PluFP, Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
select Objekat, Sifra, [ID], PluFP, Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv 
	from dbo.zaKasuPos
	where not exists (select Objekat, Sifra from dbo.ArhivaZaPos ar 
		where Objekat = zaKasuPos.Objekat and [Sifra] = zaKasuPos.[Sifra])


GO

/****** Object:  StoredProcedure [dbo].[KasaAPrepis]    Script Date: 09/26/2010 23:36:54 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


/*dodatak za izmenu strukture*/
SET NUMERIC_ROUNDABORT OFF
GO
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
SET XACT_ABORT ON
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
GO
ALTER TABLE [dbo].[Zakljucenja] DROP CONSTRAINT [PK_Zakljucenja]
GO
ALTER TABLE [dbo].[Izlaz0] DROP CONSTRAINT [DF_Izlaz0_TipkPDV]
GO
ALTER TABLE [dbo].[Izlaz0] DROP CONSTRAINT [DF_Izlaz0_TipuPDV]
GO
ALTER TABLE [dbo].[KasaFP] DROP CONSTRAINT [DF_KasaFP_LastEditDate]
GO
ALTER TABLE [dbo].[KasaFP] DROP CONSTRAINT [DF_KasaFP_CreationDate]
GO
--ALTER TABLE [dbo].[KasaFP] DROP CONSTRAINT [DF_KasaFP_Povrat]
--GO
ALTER TABLE [dbo].[KasaFP] DROP CONSTRAINT [DF__KasaFP__PopustNaRacun]
GO
--ALTER TABLE [dbo].[KasaFP] DROP CONSTRAINT [DF__KasaFP__Stornira__3AE27131]
--GO
--ALTER TABLE [dbo].[KasaFP] DROP CONSTRAINT [DF__KasaFP__Poslato__3BD6956A]
--GO
ALTER TABLE [dbo].[KasaFPSt] DROP CONSTRAINT [DF_KasaFPSt_LastEditDate]
GO
ALTER TABLE [dbo].[KasaFPSt] DROP CONSTRAINT [DF_KasaFPSt_CreationDate]
GO
ALTER TABLE [dbo].[KasaFPSt] ALTER COLUMN [LastEditDate] [datetime] NULL
ALTER TABLE [dbo].[KasaFPSt] ALTER COLUMN [CreationDate] [datetime] NULL
GO
ALTER TABLE [dbo].[KasaFP] ALTER COLUMN [LastEditDate] [smalldatetime] NULL
ALTER TABLE [dbo].[KasaFP] ALTER COLUMN [CreationDate] [smalldatetime] NULL
ALTER TABLE [dbo].[KasaFP] ALTER COLUMN [Povrat] [bit] NULL
ALTER TABLE [dbo].[KasaFP] ALTER COLUMN [PopustNaRacun] [numeric] (10, 2) NULL
ALTER TABLE [dbo].[KasaFP] ALTER COLUMN [Stornirano] [bit] NULL
ALTER TABLE [dbo].[KasaFP] ALTER COLUMN [Poslato] [bit] NULL
GO
ALTER TABLE [dbo].[Zakljucenja] ALTER COLUMN [Datum] [datetime] NOT NULL
ALTER TABLE [dbo].[Zakljucenja] ALTER COLUMN [SisDatum] [datetime] NULL
GO
ALTER TABLE [dbo].[Zakljucenja] ADD CONSTRAINT [PK_Zakljucenja] PRIMARY KEY CLUSTERED  ([Objekat], [Kasa], [Datum], [Zakljucenje])
GO
ALTER TABLE [dbo].[zaKasuPOS] ALTER COLUMN [Bar_cod] [varchar] (14) COLLATE Slovenian_CI_AS NULL
GO
ALTER TABLE [dbo].[Izlaz0] ALTER COLUMN [TipkPDV] [tinyint] NULL
ALTER TABLE [dbo].[Izlaz0] ALTER COLUMN [TipuPDV] [tinyint] NULL
GO
CREATE PROCEDURE dbo.KasaAPrepis
	@Broj INT
AS
	SET NOCOUNT ON ;
	DECLARE @BrojNovi INT
	DECLARE @Kasa VARCHAR(3) 
	SET @Kasa = ( SELECT   Kasa
			   FROM     dbo.KasaA
			   WHERE    Broj = @Broj
			 )
	IF	@Kasa IS NULL
		RETURN;
	SET @BrojNovi = ( SELECT   MAX(Broj) br
				   FROM     dbo.KasaFP
				   WHERE    Kasa = @Kasa
				 )
	SET @BrojNovi = ISNULL(@BrojNovi, 0) + 1
	IF	@BrojNovi = 1
		SET @BrojNovi = CONVERT(int, @Kasa + '000001')
	INSERT INTO dbo.KasaFP
		( Broj ,
		  Dokument ,
		  Datum ,
		  Iznos ,
		  IznosPDV ,
		  Placanje ,
		  Promena ,
		  Partner ,
		  Valuta ,
		  Protokol ,
		  Knjizeno ,
		  ok ,
		  Operater ,
		  Objekat ,
		  Kasa ,
		  Zakljucenje ,
		  SysDatum ,
		  Iznos2 ,
		  Gotovina ,
		  Kartica ,
		  Racun ,
		  Kredit ,
		  Opis ,
		  Faktura ,
		  ExterniBroj ,
		  ExterniPromena ,
		  CardID ,
		  PoslatNaFP ,
		  ZakljucenDan ,
		  LastEditDate ,
		  CreationDate ,
		  BrojKartice ,
		  PosTerminal ,
		  Zamena ,
		  Povrat ,
		  BrojRata ,
		  PopustNaRacun ,
		  PartnerPopust ,
		  Stornirano ,
		  Poslato ,
		  ValidacijaID
		        
		)
		SELECT  @BrojNovi broj ,
				Dokument ,
				Datum ,
				Iznos ,
				IznosPDV ,
				Placanje ,
				Promena ,
				Partner ,
				Valuta ,
				Protokol ,
				Knjizeno ,
				ok ,
				Operater ,
				Objekat ,
				Kasa ,
				Zakljucenje ,
				SysDatum ,
				Iznos2 ,
				Gotovina ,
				Kartica ,
				Racun ,
				Kredit ,
				Opis ,
				Faktura ,
				@Broj ExterniBroj ,
				ExterniPromena ,
				CardID ,
				PoslatNaFP ,
				ZakljucenDan ,
				LastEditDate ,
				CreationDate ,
				BrojKartice ,
				PosTerminal ,
				Zamena ,
				Povrat ,
				BrojRata ,
				PopustNaRacun ,
				PartnerPopust ,
				Stornirano ,
				Poslato ,
				ValidacijaID
		FROM    dbo.KasaA a
		WHERE   a.Broj = @Broj
	DECLARE @tbl AS TABLE
	(
	  Broj INT ,
	  RedBroj INT ,
	  BrojI INT IDENTITY(1, 1)
	)
	INSERT INTO @tbl
		( Broj ,
		  RedBroj 
		)
		SELECT  Broj ,
				RedBroj
		FROM    dbo.KasaASt
	INSERT INTO dbo.KasaFPSt
		( Broj ,
		  RedBroj ,
		  Sifra ,
		  Kolicina ,
		  Cena ,
		  Rabat ,
		  TarifaA ,
		  Stopa ,
		  Operater ,
		  Storno ,
		  Kasa ,
		  Zakljucenje ,
		  LastEditDate ,
		  CreationDate
		        
		)
		SELECT  @BrojNovi Broj ,
				t.BrojI RedBroj ,
				Sifra ,
				Kolicina ,
				Cena ,
				Rabat ,
				TarifaA ,
				Stopa ,
				Operater ,
				Storno ,
				Kasa ,
				Zakljucenje ,
				LastEditDate ,
				CreationDate
		FROM    dbo.KasaASt st
				INNER JOIN @tbl t ON st.Broj = t.Broj
									 AND st.RedBroj = t.RedBroj
--ažuriraj zaključenje i zalihe
		UPDATE dbo.KasaFPSt SET 
			Kasa = z.Kasa
			, Zakljucenje = z.Zakljucenje 
			, Operater = z.Operater
		FROM dbo.KasaFP z 
		WHERE z.Broj = dbo.KasaFPSt.Broj AND z.Broj = @BrojNovi;    

		BEGIN TRY
			UPDATE dbo.ArtikliFP SET Zalihe = Zalihe - t.kol
			FROM (SELECT Sifra, SUM(Kolicina) kol FROM dbo.KasaFPSt 
					WHERE  Broj IN (SELECT broj FROM dbo.KasaFPSt i WHERE i.Broj = @BrojNovi) GROUP BY Sifra) t
				WHERE dbo.ArtikliFP.Sifra = t.Sifra
		END TRY
		BEGIN CATCH

		END CATCH
		DELETE FROM dbo.KasaASt WHERE Broj = @Broj
		DELETE FROM dbo.KasaA WHERE Broj = @Broj
GO

-- konačna verzija prepisa artikala na fp
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[ArtikliFPPrepis]
	@Obj as nvarchar(6) = '1'
AS
SET NOCOUNT ON;

-- prvo ubaci nove artikle
insert into ArtikliFP 
	(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija, PluVaga, Tip)
select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija, a.PLU, a.Tip 
from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra);

-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Cena <> Round(s.CenaS,2)

-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
Update afp set afp.Zalihe = s.Zalihe
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Zalihe <> s.Zalihe

-- azuriraj nazive ako su menjani
Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.NazivArtikla <> a.NazivArtikla


-- tarife poreza
Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	inner join Tarife T on a.Tarifa = T.Tarifa
	where afp.Tarifa <> T.TarifaA

-- azuriraj slobodnu cenu ako je markiran
Update afp set afp.SlobodnaCena = a.SlobodnaCena
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Marker <> 0 AND afp.Cena <> 0;

-- azuriraj barkod ili jedinicu mere
Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm, afp.PluVaga = a.PLU, afp.Tip = a.Tip
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Barkod <> a.Barkod or afp.jm <> a.jm OR afp.PluVaga <> a.PLU OR afp.Tip <> a.Tip

-- upis u zaKasaPos svih izmena
TRUNCATE TABLE dbo.zaKasuPOS;
INSERT INTO dbo.zaKasuPOS
        ( Objekat ,
			Sifra,
          ID ,
          PluFP,
          Bar_cod ,
          PLU_Naziv ,
          Cena ,
          Tarifa ,
          Ind_deckol ,
          Ind_otv ,
          Unos_l
        )
SELECT @Obj AS objekat
	, a.Sifra
	, CONVERT(VARCHAR(10), a.Sifra) ID
	, a.Plu
	, a.Barkod
	, LEFT(a.NazivArtikla, 50)
	, Round(a.Cena,2) Cena
	, a.Tarifa
	, CASE WHEN a.Decimale <> 0 THEN 'D' ELSE 'N' END 
	, CASE WHEN a.SlobodnaCena <> 0 THEN 'D' ELSE 'N' END 
	, 'N' Unos_L
from ArtikliFP a
WHERE NOT a.Sifra IN (SELECT CAST(arh.ID AS INT) Sifra FROM dbo.ArhivaZaPos arh WHERE arh.Objekat = @Obj)
AND a.Cena <> 0

INSERT INTO dbo.zaKasuPOS
        ( Objekat ,
			Sifra,
          ID ,
          PluFP,
          Bar_cod ,
          PLU_Naziv ,
          Cena ,
          Tarifa ,
          Ind_deckol ,
          Ind_otv ,
          Unos_l
        )
SELECT @Obj AS objekat
	, a.Sifra
	, CONVERT(VARCHAR(10), a.Sifra) ID
	, a.Plu
	, a.Barkod
	, LEFT(a.NazivArtikla, 50)
	, Round(a.Cena,2) Cena
	, a.Tarifa
	, CASE WHEN a.Decimale <> 0 THEN 'D' ELSE 'N' END 
	, CASE WHEN a.SlobodnaCena <> 0 THEN 'D' ELSE 'N' END 
	, a.Unos_L
from ArtikliFP a
INNER join (SELECT CAST(ID AS INT) AS Sifra, PLU_Naziv, Cena, Bar_cod, Tarifa FROM dbo.ArhivaZaPos WHERE Objekat = @Obj) s on a.Sifra = s.Sifra
WHERE ( LEFT(a.NazivArtikla, 50) <> s.PLU_Naziv OR 
	a.Cena <> s.Cena
	OR a.Barkod <> s.Bar_cod)
	OR a.Tarifa <> s.Tarifa
EXEC dbo.pos_UpisUDnevnik @Broj = 0, @Promena = 0
EXEC dbo.pos_UpisUArhivazaPos
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[ArtikliFPPrepisKalkMP]
	@Broj as INT
AS

SET NOCOUNT ON;
DECLARE @Obj AS NVARCHAR(6)
DECLARE @Objekat AS NVARCHAR(6)
DECLARE @Promena AS INT
SELECT @Obj = Objekat, @Promena = Promena FROM KalkMP0 WHERE Broj = @Broj
IF @Obj IS NULL 
	RETURN;
SET @Objekat = @Obj
-- prvo ubaci nove artikle
insert into ArtikliFP 
	(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija, PluVaga, Tip)
select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija, a.PLU, a.Tip 
from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra)
	AND a.Sifra IN (SELECT Sifra FROM KalkMP WHERE Broj = @Broj);

-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Cena <> Round(s.CenaS,2)

-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
Update afp set afp.Zalihe = s.Zalihe
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Zalihe <> s.Zalihe
-- azuriraj nazive ako su menjani
Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.NazivArtikla <> a.NazivArtikla
-- tarife poreza
Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	inner join Tarife T on a.Tarifa = T.Tarifa
	where afp.Tarifa <> T.TarifaA


-- azuriraj barkod ili jedinicu mere
Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm, afp.PluVaga = a.PLU, afp.Tip = afp.Tip
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Barkod <> a.Barkod or afp.jm <> a.jm OR afp.PluVaga <> a.PLU OR afp.Tip <> a.Tip

-- azuriraj slobodnu cenu ako je markiran
Update afp set afp.SlobodnaCena = a.SlobodnaCena
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Marker <> 0;

-- Prepis u Arhivu za Pos i Dnevnik
TRUNCATE TABLE dbo.zaKasuPOS;
SELECT DISTINCT Sifra, (select TOP 1 PrCenaKom FROM dbo.KalkMp K WHERE k.Broj = kst.Broj AND k.Sifra = kst.Sifra) AS ProdCena 
INTO #Cene
FROM dbo.KalkMp kst WHERE Broj = @Broj

insert into dbo.ZaKasuPos (Objekat, Sifra, [ID], PluFP, Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
select @Obj as Objekat, a.Sifra, CONVERT(VARCHAR(10), a.Sifra), a.Plu, a.Barkod, 
	Left(a.NazivArtikla, 50) as nn, c.ProdCena, 
	a.Tarifa , 
	'N' as Unos_l, 
	ind_deckol = case when a.Decimale = 0 THEN 'N' WHEN a.Decimale <> 0 THEN 'D' END, 
	ind_otv = case when a.SlobodnaCena = 0 THEN 'N' WHEN a.SlobodnaCena <> 0 THEN 'D' END 
From ArtikliFp a Inner Join #Cene c On a.Sifra = c.Sifra

DROP TABLE #Cene

UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'P' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena <> ArhivazaPOS.Cena
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'C' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod <> ArhivazaPOS.Bar_cod) OR (zaKasuPos.PLU_naziv <> ArhivazaPOS.PLU_naziv)  OR (zaKasuPos.Tarifa <> ArhivazaPOS.Tarifa)) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND (zaKasuPos.Bar_cod = ArhivazaPOS.Bar_cod) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod is null) and (ArhivazaPOS.Bar_cod is null)) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv)

-- prepis u ArhivaZaPosDnevnik
EXEC dbo.pos_UpisUDnevnik @Broj, @Promena

EXEC dbo.pos_UpisUArhivazaPos
GO

/****** Object:  StoredProcedure [dbo].[ArtikliFPPrepisNivelMP]    Script Date: 10/24/2010 16:55:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[ArtikliFPPrepisNivelMP]
	@Broj as INT
AS

DECLARE @Obj AS NVARCHAR(6)
DECLARE @Objekat AS NVARCHAR(6)
DECLARE @Promena AS INT

SELECT @Obj = Objekat, @Promena = Promena FROM NivelMP0 WHERE Broj = @Broj
IF @Obj IS NULL 
	RETURN;
SET @Objekat = @Obj
-- prvo ubaci nove artikle
insert into ArtikliFP 
	(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija, PluVaga, Tip)
select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija, a.PLU, a.Tip 
from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra)
	AND a.Sifra IN (SELECT Sifra FROM NivelMP WHERE Broj = @Broj);

-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Cena <> Round(s.CenaS,2)

-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
Update afp set afp.Zalihe = s.Zalihe
	from ArtikliFP afp inner join 
	(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
	where afp.Zalihe <> s.Zalihe
-- azuriraj nazive ako su menjani
Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.NazivArtikla <> a.NazivArtikla
-- tarife poreza
Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	inner join Tarife T on a.Tarifa = T.Tarifa
	where afp.Tarifa <> T.TarifaA


-- azuriraj barkod ili jedinicu mere
Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm, afp.PluVaga = a.Plu, afp.Tip = a.Tip
	from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
	where afp.Barkod <> a.Barkod or afp.jm <> a.jm OR afp.PluVaga <> a.PLU OR afp.Tip <> a.Tip

TRUNCATE TABLE dbo.zaKasuPOS;

SELECT DISTINCT Sifra, Cena AS ProdCena 
INTO #Cene
FROM dbo.NivelMP WHERE Broj = @Broj

insert into dbo.ZaKasuPos (Objekat, Sifra, [ID], PluFP, Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
select @Obj as Objekat, a.Sifra, CONVERT(VARCHAR(10), a.Sifra), a.PluFP, a.Barkod, 
	Left(a.NazivArtikla, 50) as nn, c.ProdCena, 
	t.TarifaA , 
	'N' as Unos_l, 
	ind_deckol = case when a.Decimale = 0 THEN 'N' WHEN a.Decimale <> 0 THEN 'D' END, 
	ind_otv = case when a.SlobodnaCena = 0 THEN 'N' WHEN a.SlobodnaCena <> 0 THEN 'D' END 
From Tarife t Inner Join (Artikli a Inner Join #Cene c On a.Sifra = c.Sifra) On t.Tarifa = a.Tarifa

DROP TABLE #Cene

UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'P' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena <> ArhivazaPOS.Cena
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'C' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod <> ArhivazaPOS.Bar_cod) OR (zaKasuPos.PLU_naziv <> ArhivazaPOS.PLU_naziv)  OR (zaKasuPos.Tarifa <> ArhivazaPOS.Tarifa)) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND (zaKasuPos.Bar_cod = ArhivazaPOS.Bar_cod) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv) 
UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod is null) and (ArhivazaPOS.Bar_cod is null)) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv)

EXEC dbo.pos_UpisUDnevnik @Broj, @Promena

EXEC dbo.pos_UpisUArhivazaPos
GO

/****** Object:  StoredProcedure [dbo].[ArtikliFPPrepisPopis]    Script Date: 10/24/2010 17:00:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[ArtikliFPPrepisPopis]
	@Broj as INT
AS

DECLARE @Obj AS NVARCHAR(6)
DECLARE @Objekat AS NVARCHAR(6)
DECLARE @Promena AS INT

SELECT @Obj = Objekat, @Promena = Promena FROM dbo.Popis0 WHERE Broj = @Broj
IF @Obj IS NULL 
	RETURN;
SET @Objekat = @Obj
BEGIN TRAN
BEGIN TRY
	-- prvo ubaci nove artikle
	insert into ArtikliFP 
		(Sifra, Artikal, Plu, NazivArtikla, JM, Tarifa, Cena, Barkod, Zalihe, Kategorija, PluVaga, Tip)
	select a.Sifra, a.Artikal, a.PluFP, LEFT(a.NazivArtikla, 50), a.JM, t.TarifaA Tarifa, Round(s.CenaS,2) Cena, a.Barkod, s.Zalihe, a.Kategorija, a.PLU, a.Tip 
	from Artikli a inner join Tarife t on a.Tarifa = t.Tarifa
	inner join (Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on a.Sifra = s.SifraS
	WHERE Not Exists (Select Sifra from ArtikliFP afp where Sifra = a.Sifra)
		AND a.Sifra IN (SELECT Sifra FROM dbo.Popis WHERE Broj = @Broj);

	-- ako je neka cena menjana onda je azuriraj i markiraj artikal kao promenjenu cenu
	Update afp set afp.Cena = Round(s.CenaS,2), Marker = 1, Unos_L = 'P'
		from ArtikliFP afp inner join 
		(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
		where afp.Cena <> Round(s.CenaS,2)

	-- azuriraj zalihe ali nemoj nista markirati jer se zalihe sve salju na FP
	Update afp set afp.Zalihe = s.Zalihe
		from ArtikliFP afp inner join 
		(Select Sifra SifraS, Zalihe, Cena CenaS from Stanje Where Objekat = @Obj) s on afp.Sifra = s.SifraS
		where afp.Zalihe <> s.Zalihe
	-- azuriraj nazive ako su menjani
	Update afp set afp.NazivArtikla = a.NazivArtikla, Marker = 1, Unos_L = 'C'
		from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
		where afp.NazivArtikla <> a.NazivArtikla
	-- tarife poreza
	Update afp set afp.Tarifa = T.TarifaA, Marker = 1, Unos_L = 'C'
		from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
		inner join Tarife T on a.Tarifa = T.Tarifa
		where afp.Tarifa <> T.TarifaA


	-- azuriraj barkod ili jedinicu mere
	Update afp set afp.Barkod = a.Barkod, afp.Jm = a.jm, afp.PluVaga = a.PLU, afp.Tip = a.Tip
		from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
		where afp.Barkod <> a.Barkod or afp.jm <> a.jm OR afp.PluVaga <> a.PLU OR afp.Tip <> a.Tip
	-- azuriraj slobodnu cenu ako je markiran
	Update afp set afp.SlobodnaCena = a.SlobodnaCena
		from ArtikliFP afp inner join Artikli a on afp.Sifra = a.Sifra
		where afp.Marker <> 0;

	TRUNCATE TABLE dbo.zaKasuPOS;

	SELECT DISTINCT Sifra, Cena AS ProdCena 
	INTO #Cene
	FROM dbo.Popis WHERE Broj = @Broj

	insert into dbo.ZaKasuPos (Objekat, Sifra, [ID], Bar_cod, PLU_Naziv, Cena, Tarifa, Unos_l, ind_deckol, ind_otv)
	select @Obj as Objekat, a.Sifra, CONVERT(VARCHAR(10), a.Sifra), a.Barkod, 
		Left(a.NazivArtikla, 50) as nn, c.ProdCena, 
		t.TarifaA , 
		'N' as Unos_l, 
		ind_deckol = case when a.Decimale = 0 THEN 'N' WHEN a.Decimale <> 0 THEN 'D' END, 
		ind_otv = case when a.SlobodnaCena = 0 THEN 'N' WHEN a.SlobodnaCena <> 0 THEN 'D' END 
	From Tarife t Inner Join (Artikli a Inner Join #Cene c On a.Sifra = c.Sifra) On t.Tarifa = a.Tarifa

	DROP TABLE #Cene
	UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'P' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena <> ArhivazaPOS.Cena
	UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'C' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod <> ArhivazaPOS.Bar_cod) OR (zaKasuPos.PLU_naziv <> ArhivazaPOS.PLU_naziv)  OR (zaKasuPos.Tarifa <> ArhivazaPOS.Tarifa)) 
	UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND (zaKasuPos.Bar_cod = ArhivazaPOS.Bar_cod) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv) 
	UPDATE zaKasuPos Set zaKasuPos.Unos_l = N'0' from ArhivazaPOS where zaKasuPos.ID = ArhivazaPOS.ID and zaKasuPos.Objekat = @Objekat And zaKasuPos.Cena = ArhivazaPOS.Cena AND ((zaKasuPos.Bar_cod is null) and (ArhivazaPOS.Bar_cod is null)) and (zaKasuPos.PLU_naziv = ArhivazaPOS.PLU_naziv)

	-- prepis u ArhivaZaPosDnevnik
	EXEC dbo.pos_UpisUDnevnik @Broj, @Promena
	EXEC dbo.pos_UpisUArhivazaPos
	COMMIT TRAN
END TRY
BEGIN CATCH
	ROLLBACK TRAN
	RAISERROR ('Dokument nije pravilno poslat na POS sistem', 2, 1) 
	RETURN -1;
END CATCH
RETURN
GO

ALTER TABLE [dbo].[Izlaz0] ADD CONSTRAINT [DF_Izlaz0_TipkPDV] DEFAULT ((0)) FOR [TipkPDV]
GO
ALTER TABLE [dbo].[Izlaz0] ADD CONSTRAINT [DF_Izlaz0_TipuPDV] DEFAULT ((0)) FOR [TipuPDV]
GO
ALTER TABLE [dbo].[KasaFP] ADD CONSTRAINT [DF_KasaFP_LastEditDate] DEFAULT (getdate()) FOR [LastEditDate]
GO
ALTER TABLE [dbo].[KasaFP] ADD CONSTRAINT [DF_KasaFP_CreationDate] DEFAULT (getdate()) FOR [CreationDate]
GO
ALTER TABLE [dbo].[KasaFP] ADD CONSTRAINT [DF__KasaFP__PopustNaRacun] DEFAULT ((0)) FOR [PopustNaRacun]
GO
--ALTER TABLE [dbo].[KasaFP] ADD CONSTRAINT [DF__KasaFP__Stornira__5D42762D] DEFAULT ((0)) FOR [Stornirano]
--GO
--ALTER TABLE [dbo].[KasaFP] ADD CONSTRAINT [DF__KasaFP__Poslato__5E369A66] DEFAULT ((0)) FOR [Poslato]
--GO
ALTER TABLE [dbo].[KasaFPSt] ADD CONSTRAINT [DF_KasaFPSt_LastEditDate] DEFAULT (getdate()) FOR [LastEditDate]
GO
ALTER TABLE [dbo].[KasaFPSt] ADD CONSTRAINT [DF_KasaFPSt_CreationDate] DEFAULT (getdate()) FOR [CreationDate]
GO
ALTER TRIGGER [dbo].[KasaFP_InsertTrigger] 
    ON [dbo].[KasaFP] 
    AFTER INSERT 
AS 
BEGIN 
    SET NOCOUNT ON 
    UPDATE [dbo].[KasaFP] 
    SET [CreationDate] = GETDATE() 
    FROM inserted 
    WHERE inserted.[Broj] = [dbo].[KasaFP].[Broj] 
END;
GO
ALTER TRIGGER [dbo].[KasaFP_UpdateTrigger] 
    ON [dbo].[KasaFP] 
    AFTER UPDATE 
AS 
BEGIN 
    SET NOCOUNT ON 
    UPDATE [dbo].[KasaFP] 
    SET [LastEditDate] = GETDATE() 
    FROM inserted 
    WHERE inserted.[Broj] = [dbo].[KasaFP].[Broj] 
    -- Markiraj u stavkama broj kase, zaključenje i operatera
    -- kad se ažirira polje PoslatNaFP
	IF UPDATE(PoslatNaFP)
	BEGIN
		UPDATE dbo.KasaFPSt SET 
			Kasa = z.Kasa
			, Zakljucenje = z.Zakljucenje 
			, Operater = z.Operater
		FROM inserted z 
		WHERE z.Broj = dbo.KasaFPSt.Broj;    

		BEGIN TRY
			UPDATE dbo.ArtikliFP SET Zalihe = Zalihe - t.kol
			FROM (SELECT Sifra, SUM(Kolicina) kol FROM dbo.KasaFPSt 
					WHERE  Broj IN (SELECT broj FROM INSERTED i) GROUP BY Sifra) t
				WHERE dbo.ArtikliFP.Sifra = t.Sifra
		END TRY
		BEGIN CATCH

		END CATCH
	END
END;
GO

ALTER TRIGGER [dbo].[KasaFPSt_InsertTrigger] 
    ON [dbo].[KasaFPSt] 
    AFTER INSERT 
AS 
BEGIN 
    SET NOCOUNT ON 
    UPDATE [dbo].[KasaFPSt] 
    SET [CreationDate] = GETDATE() 
    FROM inserted 
    WHERE inserted.[Broj] = [dbo].[KasaFPSt].[Broj] 
    AND inserted.[RedBroj] = [dbo].[KasaFPSt].[RedBroj] 
END;


GO

ALTER TRIGGER [dbo].[KasaFPSt_UpdateTrigger] 
    ON [dbo].[KasaFPSt] 
    AFTER UPDATE 
AS 
BEGIN 
    SET NOCOUNT ON 
    UPDATE [dbo].[KasaFPSt] 
    SET [LastEditDate] = GETDATE() 
    FROM inserted 
    WHERE inserted.[Broj] = [dbo].[KasaFPSt].[Broj] 
    AND inserted.[RedBroj] = [dbo].[KasaFPSt].[RedBroj] 
END;


GO
-- =============================================
-- Author:		<Author,,Dejan Dabić>
-- ALTER  date: <ALTER  Date,, 4/2/2007>
-- Description:	<Description,, Knjizenje prodaje iz marketa (Izlaz)
-- =============================================
CREATE PROCEDURE [dbo].[posB_KnjiziProdaju] (@lBroj int)
AS
BEGIN
	
	SET NOCOUNT ON;
	DECLARE @MaxBroj int, @MaxProtokol int, @i int, @Iznos money
	DECLARE @Prodavnica nvarchar(3), @Part as nvarchar(8)
	DECLARE @KnjiziTK  bit
-- ovde promenite sifru objekta za koji se prave kalkulacije i izlazne fakture MP	
	SET @KnjiziTK  = 1
	Set @Iznos = (Select Sum(Iznos) from Izlaz where Broj = @lBroj)
	SELECT * into #t From Izlaz0 where Broj = @lBroj
	SET @Prodavnica = (select top 1 Objekat from #t)
 	SET @MaxProtokol = (SELECT Max(Protokol) as maxProt From #t)
	if @MaxProtokol is Null 
 		set @MaxProtokol = 0
	if @MaxProtokol = 0 
	BEGIN
	 	SET @MaxProtokol = (SELECT Max(Protokol) as maxProt From Robno) 
	 	if @MaxProtokol is null 
	 		set @MaxProtokol = 0
	 	SET @MaxProtokol = @MaxProtokol + 1
	END
-- proveri da li je već knjzeno
	SET @i = (select Count(*) from dbo.Robno where Protokol = @MaxProtokol)
	IF @i >= 1 -- ako postoji knjizenje / vrati zalihe pa onda obrisi knjizenja i nastavi
	BEGIN
		PRINT 'postoji knjiženje po ovoj fakturi'
-- vrati zalihe
		create table #rs0 (Objekat nvarchar(3) not null, Sifra int not null, Izlaz money, Iznos money, Cena money, CONSTRAINT [PK_tmpRs0] PRIMARY KEY  ([Objekat], [Sifra]))
		Insert Into #rs0 (Objekat, Sifra, Izlaz, Iznos, Cena)
			select Objekat, Sifra, 
				Sum(Izlaz) as Izlaz, 
				Sum(Izlaz * ProdCena) as Iznos, 
				Max(ProdCena) as Cena  
			From RobnoStavke 
			Where Protokol = @MaxProtokol Group by Objekat, Sifra
		INSERT INTO Stanje (Objekat, Sifra, Cena, Zalihe) Select Objekat, Sifra, Cena, 0 as Zalihe From #rs0 as rs where Not Exists (Select Sifra From Stanje ss Where Sifra = rs.Sifra and Objekat = rs.Objekat)	
		UPDATE Stanje Set Zalihe = Zalihe + rs.Izlaz, Vrednost = Vrednost + rs.Iznos From #rs0 as rs where Stanje.Objekat = rs.Objekat AND Stanje.Sifra = rs.Sifra
		drop table #rs0
		delete from dbo.RobnoStavke where Protokol = @MaxProtokol
		delete from dbo.Robno where Protokol = @MaxProtokol
		delete from dbo.TrgKnjiga where Protokol = @MaxProtokol
		delete from dbo.tPromet where Protokol = @MaxProtokol
		delete from dbo.Promet where Protokol = @MaxProtokol
		delete from dbo.ira where Protokol = @MaxProtokol
		Update Izlaz set Protokol = 0, Knjizeno = 0 where  Broj = @lBroj
		Update Izlaz0 set Protokol = 0, Knjizeno = 0, Ok = 0 where  Broj = @lBroj
	END
	
	UPDATE Izlaz SET NabCena = a.NabCena FROM Artikli a WHERE Izlaz.Sifra = a.Sifra AND Izlaz.Broj = @lBroj
	BEGIN TRAN
-- prepis
	set @Part = (Select top 1 Partner From #t as t)
	set @i = (select count(Partner) from Partneri where Partner = @Part)
	if @i = 0 BEGIN
		IF @Part = N'K001'
			Insert Into Partneri (Partner, NazivFirme) Values (@Part, N'CKB/POS')
		IF @Part = N'K002'
			Insert Into Partneri (Partner, NazivFirme) Values (@Part, N'NLB/POS')
		IF @Part = N'K003'
			Insert Into Partneri (Partner, NazivFirme) Values (@Part, N'Diners' )
		IF @Part not in('K001', 'K002', 'K003')
			Insert Into Partneri (Partner, NazivFirme) Values (@Part, N'Kupac ' + @Part)

	END
	INSERT INTO [dbo].[Robno]
           ([Protokol], [Broj] ,[Dokument] ,[Datum] ,[Partner] ,[Dospece] ,[Objekat] 
			,[Promena] ,[Placanje] ,[TipkPDV] ,[TipuPDV] ,[Operater] ,[Opis])
	SELECT
           @MaxProtokol as Protokol
           ,t.Broj
           ,t.Dokument
           ,t.Datum
           ,t.Partner
           ,t.Valuta
           ,t.Objekat
           ,t.Promena
           ,t.Placanje
           ,t.TipkPDV
           ,t.TipuPDV
           ,t.Operater
           ,t.Opis
		from #t as t
	IF @@ERROR <> 0 
		BEGIN 
			RAISERROR ('Nepravilno knjiženje zaglavlja Robno.', 2, 1) 
			DELETE From Robno WHERE Protokol = @MaxProtokol 
			ROLLBACK TRANSACTION 
			RETURN -1 
		END
-- KREIRAJ ODMAH STAVKU U TK DA BI SE SPRECILO RUSENJE INTEGRITETA
	IF @KnjiziTK  <> 0 BEGIN
		INSERT INTO [dbo].[TrgKnjiga]
			(Objekat, Datum, Dokument, Pazar,  
			[Partner], Protokol, Operater)
		 SELECT
			t.Objekat, t.Datum, t.Dokument, t.Iznos,  
			t.Partner, @MaxProtokol, t.Operater
			FROM #t as t
		IF @@ERROR <> 0 
			BEGIN 
				RAISERROR ('Nepravilno kreiranje stavke u Trgovačkoj knjizi.', 3, 1) 
				DELETE From TrgKnjiga WHERE Protokol = @MaxProtokol
				ROLLBACK TRANSACTION 
				RETURN -1 
			END
	END
-- prepis stavki racuna u stavke robnog
	-- problem mogu da budu artikli koji ne postoje u bazi a postoje u prodaji artikala
declare @Novih as int

	select distinct Sifra, Tarifa into #Art from dbo.Izlaz where Izlaz.Broj = @lBroj and Not Exists (Select Sifra from Artikli Where Sifra = Izlaz.Sifra)
	set @Novih = @@ROWCOUNT
	if @Novih > 0 BEGIN
		print N'Novih art ' + cast(@Novih as nvarchar(6))
		insert into Artikli (Sifra, Artikal, Tip, Status, NazivArtikla) 
			Select a.Sifra, cast(a.Sifra as nvarchar(13)), 0 as Tip, 0 as Aktivam , N'Art ' + cast(a.Sifra as nvarchar(13)) From #Art a
	END
	DROP TABLE #Art

	INSERT INTO [dbo].[RobnoStavke] ([Protokol] ,[RedBroj], [Objekat], 
		[Sifra], [Izlaz],
		[Cena], [ProdCena], [Stopa], [Rabat], [Operater])
	SELECT @MaxProtokol as Protokol, iz.RedBroj, @Prodavnica as Objekat,  
		iz.Sifra, iz.Kolicina as Izl, 
		iz.Cena, iz.Cena as ProdCena, iz.Stopa, iz.Rabat, iz.Operater
	FROM [dbo].[Izlaz] as iz WHERE iz.Broj = @lBroj;

	IF @@ERROR <> 0 
		BEGIN 
			RAISERROR ('Nepravilno kreiranje stavki robnog.', 4, 1) 
			DELETE From RobnoStavke WHERE Protokol = @MaxProtokol
			ROLLBACK TRANSACTION 
			RETURN -1 
		END
	UPDATE Izlaz0 set Protokol = @MaxProtokol, Knjizeno = 1, Ok = 1 Where Broj = @lBroj
	UPDATE Izlaz set Protokol = @MaxProtokol, Knjizeno = 1 Where Broj = @lBroj
	COMMIT TRANSACTION
-- skini zalihe
	create table #rs (Objekat nvarchar(3) not null, Sifra int not null, Izlaz money, Iznos money, Cena money, CONSTRAINT [PK_tmpRs] PRIMARY KEY  ([Objekat], [Sifra]))
	Insert Into #rs (Objekat, Sifra, Izlaz, Iznos, Cena)
		select Objekat, Sifra, 
			Sum(Izlaz) as Izlaz, 
			Sum(Izlaz * ProdCena) as Iznos, 
			Max(ProdCena) as Cena  
		From RobnoStavke 
		Where Protokol = @MaxProtokol Group by Objekat, Sifra
	INSERT INTO Stanje (Objekat, Sifra, Cena, Zalihe) Select Objekat, Sifra, Cena, 0 as Zalihe From #rs as rs where Not Exists (Select Sifra From Stanje ss Where Sifra = rs.Sifra and Objekat = rs.Objekat)	
	UPDATE Stanje Set Stanje.Zalihe = Stanje.Zalihe - rs.Izlaz, Stanje.Vrednost = Stanje.Vrednost - rs.Iznos From #rs as rs where Stanje.Objekat = rs.Objekat and Stanje.Sifra = rs.Sifra
	drop table #rs
	Select Protokol, Broj, Dokument, Datum From Robno Where Protokol = @MaxProtokol
	-- briše iz log fajla sve koji su stariji od jedan dan
	DELETE FROM dbo.ArtikliFPLog WHERE Datum < CONVERT(DATETIME, CONVERT(VARCHAR(10), DATEADD(day, -1, GETDATE()), 102), 102)
	--EXEC @RC = dbo.AzurirajLager @Prodavnica, @MaxProtokol, 0, 0
Kraj:	
	drop table #t	
	RETURN 0
Greska:
	ROLLBACK TRANSACTION
	RETURN -1
END

GO
-- DODATAK ZA KASU 12.11.2010
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TaxValue]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[TaxValue]
GO

SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO

CREATE FUNCTION [dbo].[TaxValue]
         (@brutoiznos NUMERIC(38,19),
          @stopa NUMERIC(5,2))
RETURNS NUMERIC(12,2) 
  AS  
  BEGIN 
		if (@brutoiznos = 0 OR @stopa = 0)
			return 0;
		DECLARE @NET_value AS NUMERIC(38,19)
		DECLARE @NET_value1 AS NUMERIC(38,19)
		DECLARE @SALE_value AS NUMERIC(38,19)
		DECLARE @TAX_rate AS NUMERIC(38,19)
		DECLARE @TAX_value AS NUMERIC(38,19);
		
		SET @NET_value = 0
		SET @NET_value1 = 0
		SET @SALE_value = 0
		SET @TAX_rate = 0
		SET @TAX_value = 0;

		--izračunaj poreze
		SET @SALE_value = @brutoiznos * 100;
		SET @TAX_rate = @stopa / 100;
		SET @NET_value = CEILING(@SALE_value / (1 + @TAX_rate));
		SET @NET_value1 = Round(@SALE_value / (1 + @TAX_rate), 0);
		SET @TAX_value = (@SALE_value - @NET_value1) / 100;
		return (@TAX_value)
  END

GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Dejan Dabić>
-- ALTER  date: <ALTER  Date,, 23/4/2007>
-- Description:	<Description,, Formiranje fakture i knjizenje sa kase na osnovu prosledjenog broja Fiskalnog Bona
-- =============================================
ALTER PROCEDURE [dbo].[pos2_NapraviRacun] (@lBroj int)
AS
BEGIN
	
	SET NOCOUNT ON;
	DECLARE @MaxBroj int, @MaxProtokol int, @i int, @Iznos money
	DECLARE @Prodavnica nvarchar(3), @Part as nvarchar(8)
	DECLARE @KnjiziTK  bit
	DECLARE @MaxDok as nvarchar(7) 
	declare @lBrojDok as int
	declare @maxDokument as varchar(7)
	declare @lPref as int
	DECLARE @lBroj0 as int
	set @lBroj0 = @lBroj
	declare @Pref as nvarchar(3)
	set @Pref = ISNULL((select Prefiks from VrstePromena where Promena = 211), '')
	set @lPref = len(@Pref)
 	SET @MaxBroj = (SELECT Max(Broj) as maxProt From Izlaz0) 
 	if @MaxBroj is null 
 		set @MaxBroj = 0
 	SET @MaxBroj = @MaxBroj + 1
	set @MaxDok = (select max(dokument) as dok from Izlaz0 where left(Dokument, @lPref) = @Pref and Promena = 211)
 	if @MaxDok is null 
 		--set @MaxDok = @Pref + '0001'
		set @lBrojDok = 0
	else
		set @lBrojDok = cast(substring(@maxDok, @lPref + 1, 7 - @lPref) as int)
	set @lBrojDok = @lBrojDok + 1
	SET @MaxDok = @Pref + right('000000' + CAST(@lBrojDok as varchar(5)), 7 - @lPref)
	set @Iznos = (Select Sum(Kolicina * Cena) from dbo.KasaFPSt Where Broj = @lBroj)
	if @Iznos is Null
		begin
		Select '-1' as Dokument 
		Return -1
	END
	insert into izlaz0 (Broj, Objekat, Dokument, Datum, Valuta, Promena, Placanje, [Partner], Opis, Kasa, BrojBona, Iznos)
		select @MaxBroj as Broj, rs.Objekat, @MaxDok as Dok, convert(datetime, convert(varchar(10), rs.Datum, 102), 102) as Datum, dateadd(day, 2, rs.Datum) as Valuta, 211 as Promena, 1 as Placanje, rs.Partner, 'Na osnovu Fiskalnog bona> ' + rs.Dokument, rs.Kasa, rs.Dokument, @Iznos as Iznos
			from dbo.KasaFP rs where Broj = @lBroj
	insert into izlaz (Broj, RedBroj, Sifra, Kolicina, Cena, Iznos, Rabat, Stopa, Tarifa, NabCena)
		select @MaxBroj as Broj, rs.RedBroj, rs.Sifra, rs.Kolicina, rs.Cena, ROUND(rs.Kolicina * rs.Cena, 2) AS Iznos, rs.Rabat, rs.Stopa, a.Tarifa, a.NabCena
			from dbo.KasaFPSt rs LEFT JOIN Artikli a ON rs.sifra = a.sifra
			where Broj = @lBroj
	set @lBroj = @MaxBroj
-- ovde promenite sifru objekta za koji se prave izlazne fakture MP	
	SET @KnjiziTK  = 1
	SELECT * into #t From Izlaz0 where Broj = @lBroj
	SET @Prodavnica = (select top 1 Objekat from #t)
 	SET @MaxProtokol = (SELECT Max(Protokol) as maxProt From #t)
	if @MaxProtokol is Null 
 		set @MaxProtokol = 0
	if @MaxProtokol = 0 
	BEGIN
	 	SET @MaxProtokol = (SELECT Max(Protokol) as maxProt From Robno) 
	 	if @MaxProtokol is null 
	 		set @MaxProtokol = 0
	 	SET @MaxProtokol = @MaxProtokol + 1
	END
-- proveri da li je već knjizeno
	SET @i = (select Count(*) from dbo.Robno where Protokol = @MaxProtokol)
	IF @i >= 1 -- ako postoji knjizenje / vrati zalihe pa onda obrisi knjizenja i nastavi
	BEGIN
		PRINT 'postoji knjiženje po ovoj fakturi'
-- vrati zalihe
		create table #rs0 (Objekat nvarchar(3) not null, Sifra int not null, Izlaz money, Iznos money, Cena money, CONSTRAINT [PK_tmpRs0] PRIMARY KEY  ([Objekat], [Sifra]))
		Insert Into #rs0 (Objekat, Sifra, Izlaz, Iznos, Cena)
			select Objekat, Sifra, 
				Sum(Izlaz) as Izlaz, 
				Sum(Izlaz * ProdCena) as Iznos, 
				Max(ProdCena) as Cena  
			From RobnoStavke 
			Where Protokol = @MaxProtokol Group by Objekat, Sifra
		INSERT INTO Stanje (Objekat, Sifra, Cena, Zalihe) Select Objekat, Sifra, Cena, 0 as Zalihe From #rs0 as rs where Not Exists (Select Sifra From Stanje ss Where Sifra = rs.Sifra and Objekat = rs.Objekat)	
		UPDATE Stanje Set Zalihe = Zalihe + rs.Izlaz, Vrednost = Vrednost + rs.Iznos From #rs0 as rs where Stanje.Objekat = rs.Objekat AND Stanje.Sifra = rs.Sifra
		drop table #rs0
		delete from dbo.RobnoStavke where Protokol = @MaxProtokol
		delete from dbo.Robno where Protokol = @MaxProtokol
		delete from dbo.TrgKnjiga where Protokol = @MaxProtokol
		delete from dbo.tPromet where Protokol = @MaxProtokol
		delete from dbo.Promet where Protokol = @MaxProtokol
		delete from dbo.ira where Protokol = @MaxProtokol
		Update Izlaz set Protokol = 0, Knjizeno = 0 where  Broj = @lBroj
		Update Izlaz0 set Protokol = 0, Knjizeno = 0, Ok = 0 where  Broj = @lBroj
	END
	
	BEGIN TRAN
-- prepis
	set @Part = (Select top 1 Partner From #t as t)
	set @i = (select count(Partner) from Partneri where Partner = @Part)
	if @i = 0 BEGIN
		Insert Into Partneri (Partner, NazivFirme) Values (@Part, N'Kupac ' + @Part)
	END
	INSERT INTO [dbo].[Robno]
           ([Protokol], [Broj] ,[Dokument] ,[Datum] ,[Partner] ,[Dospece] ,[Objekat] 
			,[Promena] ,[Placanje] ,[TipkPDV] ,[TipuPDV] ,[Operater] ,[Opis])
	SELECT
           @MaxProtokol as Protokol
           ,t.Broj
           ,t.Dokument
           ,t.Datum
           ,t.Partner
           ,t.Valuta
           ,t.Objekat
           ,t.Promena
           ,t.Placanje
           ,t.TipkPDV
           ,t.TipuPDV
           ,t.Operater
           ,t.Opis
		from #t as t
	IF @@ERROR <> 0 
		BEGIN 
			RAISERROR ('Nepravilno knjiženje zaglavlja Robno.', 2, 1) 
			DELETE From Robno WHERE Protokol = @MaxProtokol 
			ROLLBACK TRANSACTION 
			RETURN -1 
		END
-- KREIRAJ ODMAH STAVKU U TK DA BI SE SPRECILO RUSENJE INTEGRITETA
	IF @KnjiziTK  <> 0 BEGIN
		INSERT INTO [dbo].[TrgKnjiga]
			(Objekat, Datum, Dokument, Pazar,  
			[Partner], Protokol, Operater)
		 SELECT
			t.Objekat, t.Datum, t.Dokument, t.Iznos,  
			t.Partner, @MaxProtokol, t.Operater
			FROM #t as t
		IF @@ERROR <> 0 
			BEGIN 
				RAISERROR ('Nepravilno kreiranje stavke u Trgovačkoj knjizi.', 3, 1) 
				DELETE From TrgKnjiga WHERE Protokol = @MaxProtokol
				ROLLBACK TRANSACTION 
				RETURN -1 
			END
	END
-- prepis stavki racuna u stavke robnog
	-- problem mogu da budu artikli koji ne postoje u bazi a postoje u prodaji artikala
declare @Novih as int
	select distinct Sifra, Tarifa into #Art from dbo.Izlaz where Izlaz.Broj = @lBroj and Not Exists (Select Sifra from Artikli Where Sifra = Izlaz.Sifra)
	set @Novih = @@ROWCOUNT
	if @Novih > 0 BEGIN
		print N'Novih art ' + cast(@Novih as nvarchar(6))
		insert into Artikli (Sifra, Artikal, Tip, Status, NazivArtikla) 
			Select a.Sifra, cast(a.Sifra as nvarchar(13)), 0 as Tip, 0 as Aktivam , N'Art ' + cast(a.Sifra as nvarchar(13)) From #Art a
	END
	DROP TABLE #Art
	INSERT INTO [dbo].[RobnoStavke] ([Protokol] ,[RedBroj], [Objekat], 
		[Sifra], [Izlaz],
		[Cena], [ProdCena], [Stopa], [Rabat], [Operater], NabCena)
	SELECT @MaxProtokol as Protokol, iz.RedBroj, @Prodavnica as Objekat,  
		iz.Sifra, iz.Kolicina as Izl, 
		iz.Cena, iz.Cena as ProdCena, iz.Stopa, iz.Rabat, iz.Operater, iz.NabCena
	FROM [dbo].[Izlaz] as iz WHERE iz.Broj = @lBroj;
	IF @@ERROR <> 0 
		BEGIN 
			RAISERROR ('Nepravilno kreiranje stavki robnog.', 4, 1) 
			DELETE From RobnoStavke WHERE Protokol = @MaxProtokol
			ROLLBACK TRANSACTION 
			RETURN -1 
		END
	UPDATE Izlaz0 set Protokol = @MaxProtokol, Knjizeno = 1, Ok = 0 Where Broj = @lBroj
	UPDATE Izlaz set Protokol = @MaxProtokol, Knjizeno = 1, OKup = 1 Where Broj = @lBroj
	UPDATE dbo.KasaFP set Protokol = @MaxProtokol, Knjizeno = 1, Faktura = @MaxDok 
		Where Broj = @lBroj
	COMMIT TRANSACTION
-- skini zalihe
	create table #rs (Objekat nvarchar(3) not null, Sifra int not null, Izlaz money, Iznos money, Cena money, CONSTRAINT [PK_tmpRs] PRIMARY KEY  ([Objekat], [Sifra]))
	Insert Into #rs (Objekat, Sifra, Izlaz, Iznos, Cena)
		select Objekat, Sifra, 
			Sum(Izlaz) as Izlaz, 
			Sum(Izlaz * ProdCena) as Iznos, 
			Max(ProdCena) as Cena  
		From RobnoStavke 
		Where Protokol = @MaxProtokol Group by Objekat, Sifra
	INSERT INTO Stanje (Objekat, Sifra, Cena, Zalihe) Select Objekat, Sifra, Cena, 0 as Zalihe From #rs as rs where Not Exists (Select Sifra From Stanje ss Where Sifra = rs.Sifra and Objekat = rs.Objekat)	
	UPDATE Stanje Set Stanje.Zalihe = Stanje.Zalihe - rs.Izlaz, Stanje.Vrednost = Stanje.Vrednost - rs.Iznos From #rs as rs where Stanje.Objekat = rs.Objekat and Stanje.Sifra = rs.Sifra
	UPDATE dbo.KasaFP set Faktura = @MaxDok, ExterniBroj = @MaxBroj, Placanje = 1 
		Where Broj = @lBroj0
	drop table #rs
	--EXEC @RC = dbo.AzurirajLager @Prodavnica, @MaxProtokol, 0, 0
Kraj:	
	drop table #t	
	Select Dokument, Datum, Iznos from Izlaz0 Where Broj = @lBroj
	RETURN 0
Greska:
	ROLLBACK TRANSACTION
	RETURN -1
END

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[KasaAPrepis]
	@Broj INT
AS
	SET NOCOUNT ON ;
	DECLARE @BrojNovi INT
	DECLARE @Kasa VARCHAR(3), @Placanje TINYINT 
	SELECT   @Kasa = Kasa, @Placanje = Placanje
			   FROM     dbo.KasaA
			   WHERE    Broj = @Broj
	IF	@Kasa IS NULL
		RETURN;
	SET @BrojNovi = ( SELECT   MAX(Broj) br
				   FROM     dbo.KasaFP
				   WHERE    Kasa = @Kasa
				 )
	SET @BrojNovi = ISNULL(@BrojNovi, 0) + 1
	IF	@BrojNovi = 1
		SET @BrojNovi = CONVERT(int, @Kasa + '000001')
	INSERT INTO dbo.KasaFP
		( Broj ,
		  Dokument ,
		  Datum ,
		  Iznos ,
		  IznosPDV ,
		  Placanje ,
		  Promena ,
		  Partner ,
		  Valuta ,
		  Protokol ,
		  Knjizeno ,
		  ok ,
		  Operater ,
		  Objekat ,
		  Kasa ,
		  Zakljucenje ,
		  SysDatum ,
		  Iznos2 ,
		  Gotovina ,
		  Kartica ,
		  Racun ,
		  Kredit ,
		  Opis ,
		  Faktura ,
		  ExterniBroj ,
		  ExterniPromena ,
		  CardID ,
		  PoslatNaFP ,
		  ZakljucenDan ,
		  LastEditDate ,
		  CreationDate ,
		  BrojKartice ,
		  PosTerminal ,
		  Zamena ,
		  Povrat ,
		  BrojRata ,
		  PopustNaRacun ,
		  PartnerPopust ,
		  Stornirano ,
		  Poslato ,
		  ValidacijaID,
		  KasaABroj
		        
		)
		SELECT  @BrojNovi broj ,
				Dokument ,
				Datum ,
				Iznos ,
				IznosPDV ,
				Placanje ,
				Promena ,
				Partner ,
				Valuta ,
				Protokol ,
				Knjizeno ,
				ok ,
				Operater ,
				Objekat ,
				Kasa ,
				Zakljucenje ,
				SysDatum ,
				Iznos2 ,
				Gotovina ,
				Kartica ,
				Racun ,
				Kredit ,
				Opis ,
				Faktura ,
				ExterniBroj ,
				ExterniPromena ,
				CardID ,
				PoslatNaFP ,
				ZakljucenDan ,
				LastEditDate ,
				CreationDate ,
				BrojKartice ,
				PosTerminal ,
				Zamena ,
				Povrat ,
				BrojRata ,
				PopustNaRacun ,
				PartnerPopust ,
				Stornirano ,
				Poslato ,
				ValidacijaID,
				Broj KasaABroj
		FROM    dbo.KasaA a
		WHERE   a.Broj = @Broj
	DECLARE @tbl AS TABLE
	(
	  Broj INT ,
	  RedBroj INT ,
	  BrojI INT IDENTITY(1, 1)
	)
	INSERT INTO @tbl
		( Broj ,
		  RedBroj 
		)
		SELECT  Broj ,
				RedBroj
		FROM    dbo.KasaASt
	INSERT INTO dbo.KasaFPSt
		( Broj ,
		  RedBroj ,
		  Sifra ,
		  Kolicina ,
		  Cena ,
		  Rabat ,
		  TarifaA ,
		  Stopa ,
		  Operater ,
		  Storno ,
		  Kasa ,
		  Zakljucenje ,
		  LastEditDate ,
		  CreationDate
		        
		)
		SELECT  @BrojNovi Broj ,
				t.BrojI RedBroj ,
				Sifra ,
				Kolicina ,
				Cena ,
				Rabat ,
				TarifaA ,
				Stopa ,
				Operater ,
				Storno ,
				Kasa ,
				Zakljucenje ,
				LastEditDate ,
				CreationDate
		FROM    dbo.KasaASt st
				INNER JOIN @tbl t ON st.Broj = t.Broj
									 AND st.RedBroj = t.RedBroj
--ažuriraj zaključenje i zalihe
		UPDATE dbo.KasaFPSt SET 
			Kasa = z.Kasa
			, Zakljucenje = z.Zakljucenje 
			, Operater = z.Operater
		FROM dbo.KasaFP z 
		WHERE z.Broj = dbo.KasaFPSt.Broj AND z.Broj = @BrojNovi;    

		BEGIN TRY
			UPDATE dbo.ArtikliFP SET Zalihe = Zalihe - t.kol
			FROM (SELECT Sifra, SUM(Kolicina) kol FROM dbo.KasaFPSt 
					WHERE  Broj IN (SELECT broj FROM dbo.KasaFPSt i WHERE i.Broj = @BrojNovi) GROUP BY Sifra) t
				WHERE dbo.ArtikliFP.Sifra = t.Sifra
			--IF @Placanje = 1
				--EXEC dbo.pos2_NapraviRacun @lBroj = @BrojNovi
		END TRY
		BEGIN CATCH

		END CATCH
		DELETE FROM dbo.KasaASt WHERE Broj = @Broj
		DELETE FROM dbo.KasaA WHERE Broj = @Broj
GO


/****** Object:  View [dbo].[RacuniMpSviC]    Script Date: 11/13/2010 02:07:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/****** Object:  View [dbo].[RacuniMpSviC]    Script Date: 11/13/2010 02:07:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[RacuniMpSviPOS]'))
DROP VIEW [dbo].[RacuniMpSviPOS]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE VIEW [dbo].[RacuniMpSviPOS]
AS
SELECT     dbo.Izlaz.Broj, dbo.Izlaz.RedBroj, dbo.Artikli.Artikal, dbo.Artikli.Barkod, dbo.Artikli.Sifra, dbo.Artikli.NazivArtikla, dbo.Artikli.JM, dbo.Izlaz.Kolicina, dbo.Izlaz.Cena, 
                      CAST(ROUND(dbo.Izlaz.Cena / (1 + (dbo.Izlaz.Stopa / 100)), 4) AS NUMERIC(15,4)) AS CenaBezPdv, 
                      dbo.TaxValue((dbo.Izlaz.Kolicina * dbo.Izlaz.Cena) * (1 - dbo.Izlaz.Rabat / 100), 
                      dbo.Izlaz.Stopa) AS IznosPoreza, dbo.Izlaz.Iznos, dbo.Izlaz.Rabat, ROUND(dbo.Izlaz.Iznos * dbo.Izlaz.Rabat / 100, 2) AS RabatIz, 
                      ROUND(dbo.Izlaz.Iznos * (1 - (dbo.Izlaz.Rabat / 100)), 2) AS Ukupno,
                      dbo.Izlaz0.Dokument, 
                      dbo.Izlaz0.Datum, dbo.Izlaz0.Partner, dbo.Partneri.NazivFirme, dbo.Partneri.Mesto, dbo.Partneri.BrojPoste, dbo.Partneri.Ulica, dbo.Partneri.PIB, dbo.Partneri.RegBroj, 
                      dbo.Izlaz0.Objekat, dbo.Izlaz0.Valuta, dbo.Izlaz0.Opis, dbo.Izlaz0.TekstPre, dbo.Izlaz0.TekstPosle, dbo.Izlaz.Stopa, dbo.Izlaz.Tarifa, dbo.Izlaz0.Kasa, 
                      dbo.Izlaz0.Smena AS Zakljucenje
FROM         dbo.Izlaz0 LEFT OUTER JOIN
                      dbo.Partneri ON dbo.Izlaz0.Partner = dbo.Partneri.Partner INNER JOIN
                      dbo.Artikli RIGHT OUTER JOIN
                      dbo.Izlaz ON dbo.Artikli.Sifra = dbo.Izlaz.Sifra ON dbo.Izlaz0.Broj = dbo.Izlaz.Broj


GO


/****** Object:  View [dbo].[RacuniKasa]    Script Date: 11/12/2010 22:15:04 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

ALTER VIEW [dbo].[RacuniKasa]
AS
SELECT kst.Broj, kst.RedBroj, a.Artikal, a.Barkod, a.Sifra, a.NazivArtikla, a.JM, kst.Kolicina, 
    kst.Cena, 
    CAST(Round(kst.Cena / (1 + (kst.Stopa / 100)),4) as Numeric(15,4)) AS CenaBezPdv, 
    CAST(Round(kst.Kolicina * kst.Cena,3) AS NUMERIC(15,3)) AS Iznos, 
    kst.Rabat, 
    CAST(ROUND((kst.Kolicina * kst.Cena) * (kst.Rabat / 100), 3) AS NUMERIC(15,3)) AS RabatIz, 
    CAST(ROUND((kst.Kolicina * kst.Cena) * (1 - (kst.Rabat / 100)), 3) AS NUMERIC(15,3)) as Ukupno, 
    CAST(ROUND(((kst.Kolicina * kst.Cena) * (1 - (kst.Rabat / 100))) * Round((kst.Stopa / (kst.Stopa+100)),4), 4) AS NUMERIC(15,4)) as Porez,
    K.Dokument, K.Datum, K.Partner, P.NazivFirme, P.Mesto, P.BrojPoste, P.Ulica, P.PIB, P.RegBroj, 
    K.Objekat, K.Valuta, K.Opis, kst.Stopa, K.Promena, K.Kasa, K.Zakljucenje, K.Placanje, K.KasaABroj
FROM KasaFP AS K LEFT OUTER JOIN
     Partneri AS P ON K.Partner = P.Partner INNER JOIN
     ArtikliFP AS a RIGHT OUTER JOIN
     KasaFPSt AS kst ON a.Sifra = kst.Sifra ON K.Broj = kst.Broj LEFT OUTER JOIN
     Tarife AS t ON a.Tarifa = t.Tarifa
GO
ALTER VIEW [dbo].[pos2_PoreziPoZ]
AS

SELECT Kasa, Zakljucenje, 
	SUM(TaxA) TaxA, 
	SUM(TaxB) TaxB, 
	SUM(TaxC) TaxC, 
	SUM(TaxD) TaxD, 
	SUM(TaxE) TaxE, 
	SUM(TaxF) TaxF, 
	SUM(TaxAosn) TaxAosn, 
	SUM(TaxBosn) TaxBosn, 
	SUM(TaxCosn) TaxCosn, 
	SUM(TaxDosn) TaxDosn, 
	SUM(TaxEosn) TaxEosn, 
	SUM(TaxFosn) TaxFosn, 
	SUM(TaxAPor) TaxAPor, 
	SUM(TaxBPor) TaxBPor, 
	SUM(TaxCPor) TaxCPor, 
	SUM(TaxDPor) TaxDPor, 
	SUM(TaxEPor) TaxEPor, 
	SUM(TaxFPor) TaxFPor
FROM 
(SELECT Kasa ,
        Zakljucenje ,
        CAST(TaxAosn - TaxAPor AS MONEY) TaxA,
        CAST(TaxBosn - TaxBPor AS MONEY) TaxB,
        CAST(TaxCosn - TaxCPor AS MONEY) TaxC,
        CAST(TaxDosn - TaxDPor AS MONEY) TaxD,
        CAST(TaxEosn - TaxEPor AS MONEY) TaxE,
        CAST(TaxFosn - TaxFPor  AS MONEY) TaxF,
        TaxAosn ,
        TaxBosn ,
        TaxCosn ,
        TaxDosn ,
        TaxEosn ,
        TaxFosn ,
        TaxAPor ,
        TaxBPor ,
        TaxCPor ,
        TaxDPor ,
        TaxEPor ,
        TaxFPor 
FROM
(SELECT Kasa, Zakljucenje
	, CASE WHEN TarifaA = 'A' THEN iznos 
		ELSE 0.00 END
		AS TaxAosn
	, CASE WHEN TarifaA = 'B' THEN iznos 
		ELSE 0.00 END
		AS TaxBosn
	, CASE WHEN TarifaA = 'C' THEN iznos 
		ELSE 0.00 END
		AS TaxCosn
	, CASE WHEN TarifaA = 'D' THEN iznos 
		ELSE 0.00 END
		AS TaxDosn
	, CASE WHEN TarifaA = 'E' THEN iznos 
		ELSE 0.00 END
		AS TaxEosn
	, CASE WHEN TarifaA = 'F' THEN iznos 
		ELSE 0.00 END
		AS TaxFosn
	, CASE WHEN TarifaA = 'A' THEN ROUND(iznos * stopaPrer,2)
		ELSE 0.00 END
		AS TaxAPor
	, CASE WHEN TarifaA = 'B' THEN ROUND(iznos * stopaPrer,2)
		ELSE 0.00 END
		AS TaxBPor
	, CASE WHEN TarifaA = 'C' THEN ROUND(iznos * stopaPrer,2)
		ELSE 0.00 END
		AS TaxCPor
	, CASE WHEN TarifaA = 'D' THEN ROUND(iznos * stopaPrer,2)
		ELSE 0.00 END
		AS TaxDPor
	, CASE WHEN TarifaA = 'E' THEN ROUND(iznos * stopaPrer,2)
		ELSE 0.00 END
		AS TaxEPor
	, CASE WHEN TarifaA = 'F' THEN ROUND(iznos * stopaPrer,2)
		ELSE 0.00 END
		AS TaxFPor
 FROM
(SELECT Kasa, Zakljucenje
	, TarifaA
	, st.Stopa
	, CAST(ROUND(((st.Stopa * 100) / (st.Stopa + 100)) / 100, 4) AS NUMERIC(7,4)) stopaPrer
	, SUM((st.Kolicina * st.Cena) * (1 - (cast(st.Rabat as Money) / 100))) iznos
FROM dbo.KasaFPSt st
GROUP BY st.Kasa, st.Zakljucenje, st.Stopa, st.TarifaA) por) porezi) PorPoZ
GROUP BY Kasa, Zakljucenje
GO
