if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CostRawMaterialArrived]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[CostRawMaterialArrived]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CostRawMaterialLeft]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[CostRawMaterialLeft]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCena]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetCena]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetCena1]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetCena1]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetFIOMol]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetFIOMol]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNameSyrie]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetNameSyrie]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNormRashOsnSyria]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetNormRashOsnSyria]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNormRecNumDoc]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetNormRecNumDoc]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNumDocOtch]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetNumDocOtch]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetNumProizvZadan]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetNumProizvZadan]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetOstatok]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetOstatok]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetOstatok1]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetOstatok1]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetPredprName]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetPredprName]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetSpending]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetSpending]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetTovName]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetTovName]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetVlajnSr]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[GetVlajnSr]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[LastCenAvg]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[LastCenAvg]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[MovementSyrie]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[MovementSyrie]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[RoundCena]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[RoundCena]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[iter_intlist_to_table]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[iter_intlist_to_table]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckRemains_ExistingRawMaterial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CheckRemains_ExistingRawMaterial]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CheckRemains_ReturnToManufacturer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CheckRemains_ReturnToManufacturer]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateListArrivedGoodsReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CreateListArrivedGoodsReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CreateListGoodsReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CreateListGoodsReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindDogovor]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindDogovor]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindFlO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindFlO]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindIdOper]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindIdOper]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindIdOperN]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindIdOperN]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindIdOperNN]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindIdOperNN]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindIdOperNNN]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindIdOperNNN]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindKgr]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindKgr]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindKgrKPgr]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindKgrKPgr]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindNamePredpr]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindNamePredpr]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindNameTown]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindNameTown]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindPhoneFaxPredpr]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindPhoneFaxPredpr]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindRekvizPlat]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindRekvizPlat]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindRschetPlat]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindRschetPlat]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindSchet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindSchet]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FindStHoFl]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FindStHoFl]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FioKassir]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FioKassir]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetGoodsForReportTree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GetGoodsForReportTree]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InsUpdDocOfAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[InsUpdDocOfAccount]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InvoiceArrivalReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[InvoiceArrivalReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InvoiceReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[InvoiceReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[InvoiceTrReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[InvoiceTrReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ItogForAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ItogForAccount]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListAllArrivedGoods]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ListAllArrivedGoods]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListAllGoodsArrivedByGroup]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ListAllGoodsArrivedByGroup]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListArrivedGoodsByAssortmentReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ListArrivedGoodsByAssortmentReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListArrivedGoodsByGroupsReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ListArrivedGoodsByGroupsReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListArrivedGoodsBySelectedGoodsReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ListArrivedGoodsBySelectedGoodsReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListArrivedGoodsBySubGroupsReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ListArrivedGoodsBySubGroupsReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListByAllGoodsReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ListByAllGoodsReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListByAssortmentReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ListByAssortmentReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListByGroupsReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ListByGroupsReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListBySelectedGoodsReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ListBySelectedGoodsReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ListBySubGroupsReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[ListBySubGroupsReport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelGrOperTechnolog]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelGrOperTechnolog]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelectAccounts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelectAccounts]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelectExistingRawMaterial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelectExistingRawMaterial]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelectRawMaterialReturnToManufacturer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelectRawMaterialReturnToManufacturer]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelectRawMaterialReturnToWarehouse]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelectRawMaterialReturnToWarehouse]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelectRawMaterial_EnterRemains]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelectRawMaterial_EnterRemains]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelectSyrie]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelectSyrie]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SelectWarehouses]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SelectWarehouses]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[WriteCalculatedTotals]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[WriteCalculatedTotals]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[calcBalanceSheet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[calcBalanceSheet]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[calcRawMaterialByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[calcRawMaterialByName]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[calcTotalStr]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[calcTotalStr]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[clcCopyFormuls]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[clcCopyFormuls]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[clcCopyFormulsFact]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[clcCopyFormulsFact]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[clcFormRaschChangePlaces]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[clcFormRaschChangePlaces]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[clcMoveFields]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[clcMoveFields]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[clcReestrData]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[clcReestrData]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[countWeightAvrTurnoverBalanceSheet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[countWeightAvrTurnoverBalanceSheet]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[countWeightedAveragePrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[countWeightedAveragePrice]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[countWeightedAveragePrice1]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[countWeightedAveragePrice1]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[countWeightedAveragePriceTurn]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[countWeightedAveragePriceTurn]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[delAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[delAccount]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[delDocCaption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[delDocCaption]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[delDocString]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[delDocString]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[delDocumentFromAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[delDocumentFromAccount]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[delFactRecCaption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[delFactRecCaption]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[delFactRecString]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[delFactRecString]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[delMol]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[delMol]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[delPriznSyria]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[delPriznSyria]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[delProduction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[delProduction]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[delSyrie]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[delSyrie]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[getEnterprises_RawMaterialByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[getEnterprises_RawMaterialByName]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[getGoodsForTurnroundDoc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[getGoodsForTurnroundDoc]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[getGoodsForTurnroundDocDuplicate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[getGoodsForTurnroundDocDuplicate]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[getGoodsWeightAvrPrise]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[getGoodsWeightAvrPrise]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[getRawMaterialByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[getRawMaterialByName]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[getRegistry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[getRegistry]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[getRemainsOfGoods]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[getRemainsOfGoods]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[getcodes]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[getcodes]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[insDocString]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[insDocString]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[insFactRecCaption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[insFactRecCaption]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[insFactRecString]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[insFactRecString]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[insMol]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[insMol]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[insPriznSyria]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[insPriznSyria]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[insProduction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[insProduction]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[insSyrie]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[insSyrie]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[inssDocCaption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[inssDocCaption]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[reportRawMaterial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[reportRawMaterial]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[saveAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[saveAccount]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[saveInvoice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[saveInvoice]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[saveRemainsAvrPrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[saveRemainsAvrPrice]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selAccount]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selCalculatedData_BalanceSheet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selCalculatedData_BalanceSheet]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selDocCaption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selDocCaption]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selDocOfAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selDocOfAccount]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selDocString]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selDocString]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selFactRecCaption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selFactRecCaption]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selFactRecString]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selFactRecString]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selMol]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selMol]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selPriznSyria]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selPriznSyria]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selProduction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selProduction]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selectRawMaterialByGroups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selectRawMaterialByGroups]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selectRawMaterialByGroupsTest]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selectRawMaterialByGroupsTest]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[selectTemprRemainsRawMaterial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[selectTemprRemainsRawMaterial]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_syrCaptionPrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_syrCaptionPrint]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_syrDocPrint]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_syrDocPrint]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tchCalcWaterBegin]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[tchCalcWaterBegin]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tchCalcWaterEnd]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[tchCalcWaterEnd]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tchCopyFactRecToProizvZadan]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[tchCopyFactRecToProizvZadan]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tchCopyNormRecToFactRec]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[tchCopyNormRecToFactRec]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tchDuplicateNormRec]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[tchDuplicateNormRec]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tchRecalcRashDS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[tchRecalcRashDS]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tchRecalcRashOS]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[tchRecalcRashOS]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tchRecalcRashVyhod]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[tchRecalcRashVyhod]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tchSelectSyrie]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[tchSelectSyrie]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tchSelectSyrieMy]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[tchSelectSyrieMy]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[temprRemainsRawMaterial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[temprRemainsRawMaterial]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[updAccount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[updAccount]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[updCostRawMaterial]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[updCostRawMaterial]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[updDocCaption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[updDocCaption]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[updDocString]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[updDocString]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[updFactRecCaption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[updFactRecCaption]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[updFactRecString]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[updFactRecString]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[updMol]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[updMol]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[updPriznSyria]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[updPriznSyria]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[updProduction]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[updProduction]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[updSyrie]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[updSyrie]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[updateWeightedAveragePriceForAccounting]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[updateWeightedAveragePriceForAccounting]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[writeTotalsMovingRawMaterialByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[writeTotalsMovingRawMaterialByName]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[writeWeightedAveragePrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[writeWeightedAveragePrice]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.getcodes
@CODE_ARRIVED_OUT INT OUTPUT,
@CODE_LEFT_OUT INT OUTPUT,
@CODE_ARRIVED_IN INT OUTPUT,
@CODE_LEFT_IN INT OUTPUT,
@CODE_REMAINS INT OUTPUT
AS  
SELECT @CODE_ARRIVED_OUT = ARRIVED_OUT, @CODE_LEFT_OUT = LEFT_OUT,@CODE_ARRIVED_IN = ARRIVED_INSIDE,
@CODE_LEFT_IN = LEFT_INSIDE, @CODE_REMAINS = REMAINS
FROM technolog.dbo.gropersettings
RETURN
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE FUNCTION dbo.CostRawMaterialArrived
	(@IDSTR INT)
RETURNS DECIMAL(12,3)
AS
BEGIN
  DECLARE @Result DECIMAL(12,3)
  DECLARE @KOLF DECIMAL(12,3)
  DECLARE @CENO DECIMAL(12,3)
  DECLARE @CENPRIOBR DECIMAL(12,3)
  DECLARE @NDS DECIMAL(12,3)
  --DECLARE @SKIDPOKUP DECIMAL(12,3)
  DECLARE @SKIDPOST DECIMAL(12,3)
  DECLARE @NALTR DECIMAL(12,3)
  DECLARE @NACOPT DECIMAL(12,3)
  DECLARE @NACOBPIT DECIMAL(12,3)
  SET @Result = 0	
  SELECT  @KOLF = kolf, @CENO = ceno, @NDS = nds,   @SKIDPOST= skidpost, @NALTR = naltr,  @NACOPT = nacopt,
  @NACOBPIT = nacobpit, @CENPRIOBR = cenpriobr FROM maindatabase.dbo.docstring WHERE idstr = @IDSTR
  IF (SELECT COUNT(*) FROM technolog.dbo.tbNDS WHERE nds = @NDS) > 0
  BEGIN
     SET @Result  = (ISNULL(@KOLF,0) * ISNULL(@CENPRIOBR,0)) - (ISNULL(@KOLF,0) * ISNULL(@CENPRIOBR,0) * ISNULL(@SKIDPOST,0)/100)  	
  END
  ELSE
  BEGIN
    -- SET @Result  = ISNULL(@KOLF,0) * ((ISNULL(@CENO,0)*(1+ ISNULL(@NALTR,0)/100)) * (1+ ISNULL(@NACOPT,0)/100) * (1+ ISNULL(@NDS,0)/100))
     SET @Result  = ISNULL(@KOLF,0) * (ISNULL(@CENO,0) * (1+ ISNULL(@NACOPT,0)/100) * (1+ ISNULL(@NDS,0)/100))
  END	
  RETURN (@Result)
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.CostRawMaterialLeft  ( @DOCDATE DATETIME, @IDDOC INT, @PNT_AS_KEY INT, @IDSTR INT)
RETURNS DECIMAL(12,3)
AS
BEGIN
  DECLARE @Result DECIMAL(12,3)
  DECLARE @KOLF DECIMAL(12,3)
  DECLARE @CENO DECIMAL(12,3)
  DECLARE @CENPRIOBR DECIMAL(12,3)
  DECLARE @NDS DECIMAL(12,3)
  DECLARE @SKIDPOKUP DECIMAL(12,3)
  --DECLARE @SKIDPOST DECIMAL(12,3)
  DECLARE @NALTR DECIMAL(12,3)
  DECLARE @NACOPT DECIMAL(12,3)
  DECLARE @NACOBPIT DECIMAL(12,3)
  SET @Result = 0
  DECLARE @CODE_ARRIVED_OUT INT
  SELECT @CODE_ARRIVED_OUT = arrived_out FROM gropersettings 		
  SELECT TOP 1  @CENO = ds.ceno --,@NDS = ds.nds,  @SKIDPOKUP = ds.skidpokup, @NALTR = ds.naltr,  @NACOPT = ds.nacopt, @NACOBPIT = ds.nacobpit 
  FROM maindatabase.dbo.docstring ds
  INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc
  AND dc.viddoc = 1 AND dc.iddoc = ds.iddoc 
  AND dc.idgroper = @CODE_ARRIVED_OUT
  AND dc.datedoc <= @DOCDATE AND dc.iddoc < @IDDOC
  AND ds.pnt_as_key = @PNT_AS_KEY  ORDER BY dc.iddoc DESC
	
 SELECT  @KOLF = kolf, @NDS = nds,   @SKIDPOKUP=skidpokup, @NALTR = naltr,  @NACOPT = nacopt,
  @NACOBPIT = nacobpit, @CENPRIOBR = cenpriobr FROM maindatabase.dbo.docstring WHERE idstr = @IDSTR
  IF (SELECT COUNT(*) FROM technolog.dbo.tbNDS WHERE nds = @NDS) > 0
  BEGIN
--     SET @Result  = (ISNULL(@KOLF,0) * ISNULL(@CENO,0)) - (ISNULL(@KOLF,0) * ISNULL(@CENO,0) * ISNULL(@SKIDPOKUP,0)/100)  	
     SET @Result  = (ISNULL(@KOLF,0) * ISNULL(@CENPRIOBR,0)) - (ISNULL(@KOLF,0) * ISNULL(@CENPRIOBR,0) * ISNULL(@SKIDPOKUP,0)/100)  
  END
  ELSE
  BEGIN
     SET @Result  = ISNULL(@KOLF,0) * ((((ISNULL(@CENO,0)*(1+ ISNULL(@NALTR,0)/100)) *(1+ ISNULL(@NACOBPIT,0)/100))*
	(1+ ISNULL(@NACOPT,0)/100)) * (1+ ISNULL(@NDS,0)/100))
  END	
  RETURN (@Result)
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.GetCena (@IdMetodOcenki int,  @KodSkl int,   @PNT int ,@DateTo  datetime)  
RETURNS float AS  
BEGIN 
DECLARE @Sum   float
DECLARE @Result  float
DECLARE @PNT_AS_KEY INT
-- Возвращает цену исходя из @IdOcenki :
-- 1 - средняя цена
-- 2 - учетная цена
-- 3 - последнего поступления
IF ( @IdMetodOcenki = 1 )
BEGIN
    SELECT DISTINCT @PNT_AS_KEY = ds.PNT_As_Key
    FROM MainDataBase.dbo.DocString ds INNER JOIN
               MainDataBase.dbo.DocCaption dc ON ds.IdDoc = dc.IdDoc
    WHERE (dc.KodSkl = @KodSkl) AND ds.PNT IN
                   (     
                        SELECT st2.PNT 
                        FROM  MainDataBase.dbo.SprTovar st1 JOIN 
                        MainDataBase.dbo.SprTovar st2 ON 
                        st1.PNT = @PNT AND
                        st2.KodGr = st1.KodGr AND
                        st2.KodPGr = st1.KodPGr AND
                        st2.KodVid = st1.KodVid AND
                        st2.KodR1 = st1.KodR1 AND
                        st2.KodR2 = st1.KodR2 AND
                        st2.NameT = st1.NameT AND
                        st2.EdIzID = st1.EdIzID AND
                        ISNULL(st2.Vlajn, 0) = ISNULL(st1.Vlajn, 0) AND
                        ISNULL(st2.Jirn, 0) = ISNULL(st1.Jirn, 0)
                   )
    SELECT @Result = gr.Avr_Price
    FROM tbGoodsRemains gr
    WHERE gr.PNT_As_Key = @PNT_AS_KEY AND gr.AccountDateGoods <= @DateTo
END
ELSE IF @IdMetodOcenki = 2 OR @IdMetodOcenki = 3 OR @IdMetodOcenki = 4
BEGIN
  SELECT @Result = CenO FROM MainDatabase.dbo.SprTovar WHERE PNT = @PNT
END
RETURN IsNull(@Result,0)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.GetCena1 (@IdMetodOcenki int,  @KodSkl int,   @PNT int ,@DateTo  datetime)  
RETURNS float AS  
BEGIN 
DECLARE @Sum   float
DECLARE @Result  float
-- Возвращает цену исходя из @IdOcenki :
-- 1 - средняя цена
-- 2 - учетная цена
-- 3 - последнего поступления
IF ( @IdMetodOcenki = 1 )
BEGIN
SELECT @Sum = dbo.GetOstatok(@IdMetodOcenki, @KodSkl, @PNT, @DateTo)
IF (@Sum !=0)
 BEGIN
SELECT  @Result = SUM(CASE dc.VidDoc
  		           WHEN 1 THEN IsNull(KolF * CenO,0)
		           WHEN 2 THEN -IsNull(KolF * CenO,0)
			   END) / @Sum
	FROM MainDatabase.dbo.DocString ds
	INNER JOIN MainDatabase.dbo.DocCaption dc ON dc.IdDoc = ds.IdDoc
	WHERE dc.KodSkl = @KodSkl AND dc.DateDoc <= @DateTo AND ds.PNT IN ( SELECT t2.PNT 
	                  FROM MainDatabase.dbo.SprTovar t2
       		     	  INNER JOIN MainDatabase.dbo.SprTovar t3 ON t2.KodGr = t3.KodGr
                                           AND t2.KodPGr = t3.KodPGr AND t2.KodVid = t3.KodVid
                                           AND (t2.KodR1 = t3.KodR1) AND (t2.KodR2 = t3.KodR2) AND ( t2.NameT = t3.NameT)
	                              AND ( (t2.Jirn = t3.Jirn) OR ( (t2.Jirn IS NULL) AND (t3.Jirn IS NULL) ) ) 
                                           AND ( (t2.Vlajn = t3.Vlajn) OR ( (t2.Vlajn IS NULL) AND (t3.Vlajn IS NULL) ) ) 
		                 AND ( (t2.IdSort = t3.IdSort) OR ( (t2.IdSort IS NULL) AND (t3.IdSort IS NULL) )  )
	                  WHERE t3.PNT = @PNT)  
END
 ELSE SET @Result = 0
END
ELSE IF @IdMetodOcenki = 2 OR @IdMetodOcenki = 3 OR @IdMetodOcenki = 4
BEGIN
  SELECT @Result = CenO FROM MainDatabase.dbo.SprTovar WHERE PNT = @PNT
END
RETURN IsNull(@Result,0)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.GetFIOMol (@TabN int)  
RETURNS varchar(45) AS  
BEGIN 
RETURN (SELECT TOP 1 FIO FROM MDBNew.dbo.tbMOL WHERE TabN = @TabN)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.GetNameSyrie
	( @PNT int )
RETURNS varchar(100)
AS
BEGIN
 DECLARE @Result VARCHAR(100)
 DECLARE @Vlajn VARCHAR(10)
 SET @Vlajn = (SELECT ISNULL(CAST(t.Vlajn AS VARCHAR(10)),'')
                 FROM maindatabase.dbo.SprTovar t 
                 WHERE t.PNT = @PNT )
  IF @Vlajn <>'' AND CAST(@Vlajn AS DECIMAL(10,2)) <> 0
    SET @Vlajn = @Vlajn + '%'
  ELSE
    SET @Vlajn = ''
 SET @Result = (SELECT  RTrim(IsNULL(t.NameT,'') )+ SPACE(1) + IsNULL(s.NameSort,'') +
                 + SPACE(1) +  @Vlajn AS Syrie
                 FROM maindatabase.dbo.SprTovar t 
                 LEFT JOIN maindatabase.dbo.tbSort s ON t.IdSort = s.IdSort
                 WHERE t.PNT = @PNT)
 RETURN (@Result)
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION [dbo].[GetNormRashOsnSyria] (@IdNormRec int)  
RETURNS float AS  
BEGIN 
RETURN 
(
IsNULL((SELECT SUM(NormRash) AS NormRashOsnSyria
FROM dbo.tbNormRecString 
WHERE IdNormRec = @IdNormRec AND IdPriznSyria = 1), 0.0 )
)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.GetNormRecNumDoc (@IdEnterprise int)  
RETURNS int AS  
BEGIN 
 RETURN IsNULL((SELECT MAX(NumDoc) 
                  FROM dbo.tbNormRecCaption 
                  WHERE IdEnterprise = @IdEnterprise),0) + 1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.GetNumDocOtch(
	@KodSkl int,
	@VidDoc tinyint,
             @DocOtch bit
	)
RETURNS int
AS
begin
 declare @Result int
 set @Result = 0
 -- для определения NumDoc
 if @DocOtch = 0 
	set @Result = ( IsNull((select NumDoc from maindatabase.dbo.DocCaption
	       where IdDoc = (Select max(IdDoc) from maindatabase.dbo.DocCaption 
	                      where KodSkl= @KodSkl and VidDoc= @VidDoc)),0 ) + 1)
  
 -- для определения NumOtch
 else
 
            set @Result = ( IsNull( (Select max(NumOtch) from maindatabase.dbo.DocCaption 
	                      where KodSkl= @KodSkl ),0 ) + 1)
 RETURN (@Result)         
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.GetNumProizvZadan (@IdEnterprise int)  
RETURNS int AS  
BEGIN 
 RETURN IsNULL(
( SELECT MAX(NumProizvZadan) 
  FROM dbo.tbProizvZadan 
  WHERE IdEnterprise = @IdEnterprise )
,0) + 1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.GetOstatok (@IdMetodOcenki int, @KodSkl int,@PNT int, @DateTo datetime)  
RETURNS float AS  
BEGIN 
DECLARE @PNT_AS_KEY INT
DECLARE @Ostatok float
IF @IdMetodOcenki = 1 -- По средневзвешенным ценам
BEGIN
    SELECT DISTINCT @PNT_AS_KEY = ds.PNT_As_Key
    FROM MainDataBase.dbo.DocString ds INNER JOIN
               MainDataBase.dbo.DocCaption dc ON ds.IdDoc = dc.IdDoc
    WHERE (dc.KodSkl = @KodSkl) AND ds.PNT IN
                   (     
                        SELECT st2.PNT 
                        FROM  MainDataBase.dbo.SprTovar st1 JOIN 
                        MainDataBase.dbo.SprTovar st2 ON 
                        st1.PNT = @PNT AND
                        st2.KodGr = st1.KodGr AND
                        st2.KodPGr = st1.KodPGr AND
                        st2.KodVid = st1.KodVid AND
                        st2.KodR1 = st1.KodR1 AND
                        st2.KodR2 = st1.KodR2 AND
                        st2.NameT = st1.NameT AND
                        st2.EdIzID = st1.EdIzID AND
                        ISNULL(st2.Vlajn, 0) = ISNULL(st1.Vlajn, 0) AND
                        ISNULL(st2.Jirn, 0) = ISNULL(st1.Jirn, 0)
                   )
    SELECT @Ostatok = gr.Remains
    FROM tbGoodsRemains gr
    WHERE gr.PNT_As_Key = @PNT_AS_KEY AND gr.AccountDateGoods <= @DateTo
END
ELSE IF @IdMetodOcenki = 2 -- По учетным ценам
BEGIN
SELECT @Ostatok = SUM(CASE dc.VidDoc
  		           WHEN 1 THEN IsNull(KolF,0)
		           WHEN 2 THEN -IsNull(KolF,0)
			   END)
	FROM MainDatabase.dbo.DocString ds
	INNER JOIN MainDatabase.dbo.DocCaption dc ON dc.IdDoc = ds.IdDoc
	WHERE dc.KodSkl = @KodSkl AND dc.DateDoc <= @DateTo AND ds.PNT = @PNT
END
ELSE IF @IdMetodOcenki = 3 -- По ценам последнего приобретения
BEGIN
 SET @Ostatok = 0
END
RETURN IsNULL(@Ostatok, 0.00)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.GetOstatok1 (@IdMetodOcenki int, @KodSkl int,@PNT int, @DateTo datetime)  
RETURNS float AS  
BEGIN 
DECLARE @Ostatok float
IF @IdMetodOcenki = 1 -- По средневзвешенным ценам
BEGIN
	SELECT @Ostatok = SUM(CASE dc.VidDoc
  		                               WHEN 1 THEN IsNull(KolF,0)
		                               WHEN 2 THEN -IsNull(KolF,0)
			                 END)
	FROM MainDatabase.dbo.DocString ds
	INNER JOIN MainDatabase.dbo.DocCaption dc ON dc.IdDoc = ds.IdDoc
	WHERE dc.KodSkl = @KodSkl AND dc.DateDoc <= @DateTo AND ds.PNT IN 
                              ( SELECT t2.PNT FROM MainDatabase.dbo.SprTovar t2
             		      INNER JOIN MainDatabase.dbo.SprTovar t3 ON t2.KodGr = t3.KodGr
                                          AND  t2.KodPGr = t3.KodPGr AND t2.KodVid = t3.KodVid
		     	  AND  (t2.KodR1 = t3.KodR1)  AND  (t2.KodR2 = t3.KodR2) AND( t2.NameT = t3.NameT)	
	                             AND ( (t2.Jirn = t3.Jirn) OR ( (t2.Jirn IS NULL) AND (t3.Jirn IS NULL) ) ) 
                                          AND ( (t2.Vlajn = t3.Vlajn) OR ( (t2.Vlajn IS NULL) AND (t3.Vlajn IS NULL) ) ) 
		    	  AND ( (t2.IdSort = t3.IdSort) OR ( (t2.IdSort IS NULL) AND (t3.IdSort IS NULL) )  )
	                  WHERE t3.PNT = @PNT)  
END
ELSE IF @IdMetodOcenki = 2 -- По учетным ценам
BEGIN
SELECT @Ostatok = SUM(CASE dc.VidDoc
  		           WHEN 1 THEN IsNull(KolF,0)
		           WHEN 2 THEN -IsNull(KolF,0)
			   END)
	FROM MainDatabase.dbo.DocString ds
	INNER JOIN MainDatabase.dbo.DocCaption dc ON dc.IdDoc = ds.IdDoc
	WHERE dc.KodSkl = @KodSkl AND dc.DateDoc <= @DateTo AND ds.PNT = @PNT
END
ELSE IF @IdMetodOcenki = 3 -- По ценам последнего приобретения
BEGIN
 SET @Ostatok = 0
END
RETURN IsNULL(@Ostatok, 0.00)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


--drop FUNCTION dbo.GetPredprName
CREATE FUNCTION dbo.GetPredprName (@IdPredpr int)  
RETURNS  varchar(50)  AS  
BEGIN 
 DECLARE @Result varchar(50)
 SELECT @Result = NamePredprShort FROM maindatabase.dbo.tbPredpr WHERE IdPredpr = @IdPredpr
 RETURN (@Result)
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.GetSpending
	( @DOCDATE DATETIME, @IDDOC INT, @PNT_AS_KEY INT )
RETURNS DECIMAL
AS
BEGIN
	DECLARE @CODE_ARRIVED_OUT INT
	SELECT @CODE_ARRIVED_OUT = arrived_out FROM gropersettings 		
	DECLARE @Result INT
	SET @Result = 
	(SELECT  TOP 1 ds.ceno FROM maindatabase.dbo.docstring ds
	INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND 
	dc.viddoc = 1 AND dc.iddoc = ds.iddoc 
	AND dc.idgroper = @CODE_ARRIVED_OUT
	AND dc.datedoc <= @DOCDATE AND dc.iddoc < @IDDOC
	AND ds.pnt_as_key = @PNT_AS_KEY
	ORDER BY dc.iddoc desc )
	RETURN (@Result)
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.GetTovName (@PNT int)
RETURNS varchar(30)
AS  
BEGIN 
RETURN (SELECT NameVid + SPACE(1) + IsNULL(NameT,'')
                 FROM MDBNew.dbo.SprTovar t
                 JOIN MDBNew.dbo.SprVid v ON t.KodGr = v.KodGr AND t.KodPGr = v.KodPGr AND t.KodVid = v.KodVid
                 WHERE t.PNT = @PNT)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION [dbo].[GetVlajnSr] (@IdFactRec int)  
RETURNS float AS  
BEGIN 
-- Расчет средневзвешенной влажности
DECLARE @VlajnSr float
DECLARE @Rash float
SELECT @Rash = SUM(Rash) 
FROM dbo.tbFactRecString 
WHERE IdFactRec = @IdFactRec AND IdPriznSyria = 1 -- только для основного сырья
IF @Rash > 0
	SELECT @VlajnSr = SUM(Rash * Data)/@Rash 
	FROM dbo.tbFactRecString 
	WHERE IdFactRec = @IdFactRec AND IdPriznSyria = 1 -- только для основного сырья
ELSE
	SET @VlajnSr = 0.0
RETURN @VlajnSr
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION [dbo].[LastCenAvg] (@PNT int, @KodSkl int, @ToDate datetime)  
RETURNS decimal(13,3) AS  
BEGIN 
 declare @Result decimal(13,3)
 IF @KodSkl <> -1
 begin
    set @Result = (select max(ds.CenRoz) 
                   from maindatabase.dbo.DocString ds inner join
                   maindatabase.dbo.DocCaption dc on ds.IdDoc = dc.IdDoc 
       where  ds.PNT = @PNT and dc.KodSkl = @KodSkl
                      and dc.DateDoc = (select max(dc.DateDoc) 
                                                        from maindatabase.dbo.DocString ds inner join
                                                        maindatabase.dbo.DocCaption dc on ds.IdDoc = dc.IdDoc
                                                      where dc.KodSkl = @KodSkl and (dc.DateDoc) <=@ToDate and ds.PNT = @PNT) )
 end 
 ELSE
 begin
    set @Result = (select max(ds.CenRoz) 
                   from maindatabase.dbo.DocString ds inner join
                   maindatabase.dbo.DocCaption dc on ds.IdDoc = dc.IdDoc 
     where  ds.PNT = @PNT and dc.DateDoc = (select max(dc.DateDoc) 
                                                                                from maindatabase.dbo.DocString ds inner join
                                                                                maindatabase.dbo.DocCaption dc on ds.IdDoc = dc.IdDoc
                                                                            where (dc.DateDoc) <=@ToDate and ds.PNT = @PNT) )
 end
return IsNull(@Result,0)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION [dbo].[MovementSyrie] (@PNT int, @KodSkl int, @VidDoc tinyint, @PrOper bit, @ToDate datetime)  
RETURNS decimal (13,3) AS  
BEGIN 
 DECLARE @ret decimal(13,3)
 -- для конкретного склада 
 IF ( @KodSkl <> -1 )
 begin
  -- по оперативным данным
  if @PrOper = 1
  begin
   SET @ret = ( 
	      SELECT SUM(Kolf) 
                    From maindatabase.dbo.DocString S 
                    INNER JOIN maindatabase.dbo.DocCaption D  On S.IdDoc=D.IdDoc
                    Where  D.VidDoc=@VidDoc and D.KodSkl = @KodSkl and  D.DateDoc<=@ToDate
                    and S.PNT in  ( SELECT t2.PNT FROM MainDatabase.dbo.SprTovar t2
             		      INNER JOIN MainDatabase.dbo.SprTovar t3 ON t2.KodGr = t3.KodGr
                                          AND  t2.KodPGr = t3.KodPGr AND t2.KodVid = t3.KodVid
		     	  AND  (t2.KodR1 = t3.KodR1)  AND  (t2.KodR2 = t3.KodR2) AND( t2.NameT = t3.NameT)	
	                             AND ( (t2.Jirn = t3.Jirn) OR ( (t2.Jirn IS NULL) AND (t3.Jirn IS NULL) ) ) 
                                          AND ( (t2.Vlajn = t3.Vlajn) OR ( (t2.Vlajn IS NULL) AND (t3.Vlajn IS NULL) ) ) 
		    	  AND ( (t2.IdSort = t3.IdSort) OR ( (t2.IdSort IS NULL) AND (t3.IdSort IS NULL) )  )
	                  WHERE t3.PNT = @PNT)  
                   )
   end
  --по бухгалтерским(отчетным) данным 
  else
   begin
     SET @ret = ( 
	      SELECT SUM(Kolf) 
                    From maindatabase.dbo.DocString S 
                    INNER JOIN maindatabase.dbo.DocCaption D  On S.IdDoc=D.IdDoc
                    Where  D.VidDoc=@VidDoc and D.KodSkl = @KodSkl  and D.DateOtch<=@ToDate
                     and S.PNT in  ( SELECT t2.PNT FROM MainDatabase.dbo.SprTovar t2
             		      INNER JOIN MainDatabase.dbo.SprTovar t3 ON t2.KodGr = t3.KodGr
                                          AND  t2.KodPGr = t3.KodPGr AND t2.KodVid = t3.KodVid
		     	  AND  (t2.KodR1 = t3.KodR1)  AND  (t2.KodR2 = t3.KodR2) AND( t2.NameT = t3.NameT)	
	                             AND ( (t2.Jirn = t3.Jirn) OR ( (t2.Jirn IS NULL) AND (t3.Jirn IS NULL) ) ) 
                                          AND ( (t2.Vlajn = t3.Vlajn) OR ( (t2.Vlajn IS NULL) AND (t3.Vlajn IS NULL) ) ) 
		    	  AND ( (t2.IdSort = t3.IdSort) OR ( (t2.IdSort IS NULL) AND (t3.IdSort IS NULL) )  )
	                  WHERE t3.PNT = @PNT)  
                   )
    end
   end
-- по всем складам
ELSE
 begin
   -- по оперативным данным
  if @PrOper = 1
  begin
   SET @ret = ( 
	      SELECT SUM(Kolf) 
                    From maindatabase.dbo.DocString S 
                    INNER JOIN maindatabase.dbo.DocCaption D  On S.IdDoc=D.IdDoc
                     Where  D.VidDoc=@VidDoc and D.DateDoc<=@ToDate
                      and S.PNT in  ( SELECT t2.PNT FROM MainDatabase.dbo.SprTovar t2
             		      INNER JOIN MainDatabase.dbo.SprTovar t3 ON t2.KodGr = t3.KodGr
                                          AND  t2.KodPGr = t3.KodPGr AND t2.KodVid = t3.KodVid
		     	  AND  (t2.KodR1 = t3.KodR1)  AND  (t2.KodR2 = t3.KodR2) AND( t2.NameT = t3.NameT)	
	                             AND ( (t2.Jirn = t3.Jirn) OR ( (t2.Jirn IS NULL) AND (t3.Jirn IS NULL) ) ) 
                                          AND ( (t2.Vlajn = t3.Vlajn) OR ( (t2.Vlajn IS NULL) AND (t3.Vlajn IS NULL) ) ) 
		    	  AND ( (t2.IdSort = t3.IdSort) OR ( (t2.IdSort IS NULL) AND (t3.IdSort IS NULL) )  )
	                  WHERE t3.PNT = @PNT)  
             ) 
  end
  -- по всем складам и по бухгалтерским(отчетным) данным
  else
  begin
   SET @ret = ( 
	      SELECT SUM(Kolf) 
                    From maindatabase.dbo.DocString S 
                    INNER JOIN maindatabase.dbo.DocCaption D  On S.IdDoc=D.IdDoc
                     Where  D.VidDoc=@VidDoc  and D.DateOtch<=@ToDate
                    and S.PNT in  ( SELECT t2.PNT FROM MainDatabase.dbo.SprTovar t2
             		      INNER JOIN MainDatabase.dbo.SprTovar t3 ON t2.KodGr = t3.KodGr
                                          AND  t2.KodPGr = t3.KodPGr AND t2.KodVid = t3.KodVid
		     	  AND  (t2.KodR1 = t3.KodR1)  AND  (t2.KodR2 = t3.KodR2) AND( t2.NameT = t3.NameT)	
	                             AND ( (t2.Jirn = t3.Jirn) OR ( (t2.Jirn IS NULL) AND (t3.Jirn IS NULL) ) ) 
                                          AND ( (t2.Vlajn = t3.Vlajn) OR ( (t2.Vlajn IS NULL) AND (t3.Vlajn IS NULL) ) ) 
		    	  AND ( (t2.IdSort = t3.IdSort) OR ( (t2.IdSort IS NULL) AND (t3.IdSort IS NULL) )  )
	                  WHERE t3.PNT = @PNT)  
             ) 
  end
 end
 SET @ret = ISNULL(@ret,0)
return @ret
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE FUNCTION dbo.RoundCena (@IdOkrugl int, @Cena float)  
RETURNS float AS  
BEGIN 
DECLARE @newCena float
 IF ( @IdOkrugl = 1 )  --До тысяч рублей
  SET @newCena = ROUND(@Cena,-3)
 IF ( @IdOkrugl = 2  )--До сотен рублей
  SET @newCena = ROUND(@Cena,-2)
 IF ( @IdOkrugl = 3  )--До десятков рублей
  SET @newCena = ROUND(@Cena,-1)
 IF ( @IdOkrugl = 4  )--До целого
  SET @newCena = ROUND(@Cena,0)
 IF ( @IdOkrugl = 5 ) --До 1 зн. после зап.
  SET @newCena = ROUND(@Cena,1)
 IF ( @IdOkrugl = 6 )--До 2 зн. после зап.
  SET @newCena = ROUND(@Cena,2)
 IF ( @IdOkrugl = 7 ) --До 3 зн. после зап.
  SET @newCena = ROUND(@Cena,3)
 IF ( @IdOkrugl = 8 ) --До 4 зн. после зап.
  SET @newCena = ROUND(@Cena,4)
 IF ( @IdOkrugl = 9 )  --Розничная
    BEGIN
      IF ( (@Cena-FLOOR(@Cena / 10) * 10) < 5 )
     	SET @newCena=FLOOR(@Cena / 10) * 10
      IF ( (@Cena-FLOOR(@Cena / 10) * 10)  >= 5 )
	SET @newCena=FLOOR(@Cena / 10) * 10+10
    END
RETURN  @newCena
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  FUNCTION iter_intlist_to_table (@list ntext)
      RETURNS @tbl TABLE ( number  int NOT NULL) AS
   BEGIN
      DECLARE @pos      int,
              @textpos  int,
              @chunklen smallint,
              @str      varchar(4000),
              @tmpstr   varchar(4000),
              @leftover varchar(4000)
      SET @textpos = 1
      SET @leftover = ''
      WHILE @textpos <= datalength(@list) / 2
      BEGIN
         SET @chunklen = 4000 - datalength(@leftover) / 2
         SET @tmpstr = ltrim(@leftover + substring(@list, @textpos, @chunklen))
         SET @textpos = @textpos + @chunklen
         SET @pos = charindex(',', @tmpstr)
         WHILE @pos > 0
         BEGIN
            SET @str = substring(@tmpstr, 1, @pos - 1)
            INSERT @tbl (number) VALUES(convert(int, @str))
            SET @tmpstr = ltrim(substring(@tmpstr, @pos + 1, len(@tmpstr)))
            SET @pos = charindex(',', @tmpstr)
         END
         SET @leftover = @tmpstr
      END
      IF ltrim(rtrim(@leftover)) <> ''
         INSERT @tbl (number) VALUES(convert(int, @leftover))
      RETURN
   END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.CheckRemains_ExistingRawMaterial
@CODE_STOCK INT,
@PNT INT
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
 
	SELECT  
--v.kodgr,v.kodpgr,v.kodvid,v.kodr1,v.kodr2,v.namet,v.sort as namesort,v.vlajn,v.jirn,v.ceno,v.sertif,v.pnt,
	(v.ARRIVED_OUTSIDE+ARRIVED_INSIDE-v.LEFT_OUTSIDE-LEFT_INSIDE) AS Ostatok FROM(
	SELECT  
	--MAX(st.KodGr) AS kodgr, MAX(st.KodPGr) AS kodpgr, MAX(st.KodVid) AS kodvid, MAX(st.KodR1) AS kodr1, MAX(st.KodR2) AS kodr2,
	--MAX(ds.idstr) AS idstr, MIN(goods.namet) AS namet,MIN(goods.sort) AS sort, MIN(goods.vlajn) AS vlajn,MIN(goods.jirn) AS jirn, MAX(ds.ceno) AS ceno,MAX(st.sertif) AS sertif,MAX(ds.pnt) AS pnt,
	SUM (CASE dc.viddoc WHEN 1 THEN (CASE dc.idgroper WHEN @CODE_ARRIVED_OUT THEN ds.kolf WHEN @CODE_REMAINS THEN ds.kolf ELSE 0 END) ELSE 0 END) AS ARRIVED_OUTSIDE,
	SUM (CASE dc.viddoc WHEN 2 THEN (CASE dc.idgroper WHEN @CODE_LEFT_OUT THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_OUTSIDE,
	SUM (CASE dc.viddoc WHEN 1 THEN (CASE WHEN dc.idgroper  NOT IN (@CODE_ARRIVED_OUT, @CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS ARRIVED_INSIDE,
	SUM (CASE dc.viddoc WHEN 2 THEN (CASE WHEN dc.idgroper NOT IN (@CODE_LEFT_OUT,@CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_INSIDE
	FROM MainDatabase.dbo.docstring ds
	INNER JOIN MainDatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc --AND dc.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN,@CODE_ARRIVED_IN_1,@CODE_LEFT_IN_1) 
	AND dc.kodskl = @CODE_STOCK
	INNER JOIN MainDatabase.dbo.tbgroper grop ON grop.idgroper = dc.idgroper
	INNER JOIN MainDatabase.dbo.SprTovar st ON ds.pnt = st.pnt AND st.pnt = @PNT
	INNER JOIN technolog.dbo.tbgoods goods ON goods.id = ds.pnt_as_key
	GROUP BY ds.pnt_as_key) v

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.CheckRemains_ReturnToManufacturer
@DateDoc DATETIME,
@CODE_STOCK INT,
@PNT INT
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
--END
SELECT 
--v.kodgr,v.kodpgr,v.kodvid,v.kodr1,v.kodr2,v.pnt,v.idstr,v.namet,v.sort AS namesort,v.vlajn,v.jirn, docstring.ceno, v.sertif,
(v.ARRIVED_OUTSIDE+ v.ARRIVED_INSIDE - v.LEFT_OUTSIDE - LEFT_INSIDE ) AS Ostatok FROM(
SELECT MAX(st.KodGr) AS kodgr, MAX(st.KodPGr) AS kodpgr, MAX(st.KodVid) AS kodvid, MAX(st.KodR1) AS kodr1, MAX(st.KodR2) AS kodr2,max(ds.pnt) AS pnt,
min(goods.namet) AS namet, min(goods.sort) AS sort, min(goods.vlajn) AS vlajn, min(goods.jirn) AS jirn, max(ds.ceno) AS ceno,max(st.sertif) AS sertif,
sum (case dc.viddoc WHEN 1 THEN (CASE dc.idgroper WHEN @CODE_ARRIVED_OUT THEN ds.kolf WHEN @CODE_REMAINS THEN ds.kolf ELSE 0 END) ELSE 0 END) AS ARRIVED_OUTSIDE,
sum (case dc.viddoc WHEN 2 THEN (CASE dc.idgroper WHEN @CODE_LEFT_OUT THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_OUTSIDE,
sum (case dc.viddoc WHEN 1 THEN (CASE WHEN dc.idgroper NOT IN (@CODE_ARRIVED_OUT,@CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS ARRIVED_INSIDE,
sum (case dc.viddoc WHEN 2 THEN (CASE WHEN dc.idgroper NOT IN (@CODE_LEFT_OUT,@CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_INSIDE,
max (case dc.viddoc WHEN 1 THEN (CASE dc.idgroper WHEN @CODE_ARRIVED_OUT THEN ds.idstr WHEN @CODE_REMAINS THEN ds.idstr ELSE 0 END) ELSE 0 END) AS idstr
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc 
--AND dc.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN,@CODE_ARRIVED_IN_1,@CODE_LEFT_IN_1)  
AND dc.datedoc <= @DateDoc AND dc.kodskl = @CODE_STOCK
INNER JOIN MainDatabase.dbo.tbgroper grop ON grop.idgroper = dc.idgroper 
INNER JOIN MainDatabase.dbo.sprTovar st ON ds.pnt = st.pnt AND st.pnt = @PNT AND st.PriznSyria IS NOT NULL
INNER JOIN technolog.dbo.tbgoods goods ON goods.id = ds.pnt_as_key
GROUP BY ds.pnt_as_key) v
--, (SELECT idstr,ceno FROM MainDatabase.dbo.docstring) docstring WHERE docstring.idstr = v.idstr


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.ListByGroupsReport
@CODES_GROUPS VARCHAR(200),
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
DECLARE @SQL_TEXT VARCHAR(5000)
--MUST BE REWRITTEN
SET @SQL_TEXT =
'SELECT DISTINCT sgr.namegr AS namegr, ds.pnt_as_key,goods.namet,goods.sort,goods.vlajn,goods.jirn,sediz.ediz AS ediz, 0 as kolf, 0 as ceno,
COALESCE(NULLIF(gr.remains,NULL),0) remains, 
COALESCE(NULLIF(gr.avr_price,NULL),0) price, gr.accountDateGoods
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
INNER JOIN MainDatabase.dbo.sprtovar st ON ds.pnt = st.pnt
INNER JOIN MainDatabase.dbo.sprGrup sgr ON st.kodgr = sgr.kodgr
INNER JOIN MainDatabase.dbo.sprediz sediz ON st.edizid = sediz.edizid
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
LEFT OUTER JOIN technolog.dbo.tbgoodsremains gr ON --ds.pnt_as_key = gr.pnt_as_key AND
gr.pnt_as_key = goods.id AND gr.accountDateGoods = 
(SELECT MAX(gr1.accountDateGoods) FROM technolog.dbo.tbgoodsremains gr1 WHERE gr1.pnt_as_key = gr.pnt_as_key
AND gr.accountDateGoods <= ''' + CAST(@END_DATE AS VARCHAR(12))  + ''') 
WHERE 
dc.datedoc <= ''' + CAST(@END_DATE AS VARCHAR(12)) +  ''' AND dc.datedoc >= ''' 
+ CAST(@START_DATE AS VARCHAR(12)) + '''  AND st.kodgr in (' + @CODES_GROUPS + ')'
+ ' AND dc.kodskl = '  + CAST(@CODE_WAREHOUSE AS VARCHAR(4)) 
EXEC (@SQL_TEXT)
--print @SQL_TEXT

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ListBySelectedGoodsReport
@CODES_GOODS VARCHAR(200),
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
DECLARE @SQL_TEXT VARCHAR(5000)
--MUST BE REWRITTEN
SET @SQL_TEXT =
'SELECT DISTINCT sgr.namegr AS namegr, ds.pnt_as_key,goods.namet,goods.sort,goods.vlajn,goods.jirn,sediz.ediz AS ediz, 0 as kolf, 0 as ceno,
COALESCE(NULLIF(gr.remains,NULL),0) remains, 
COALESCE(NULLIF(gr.avr_price,NULL),0) price, gr.accountDateGoods
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
INNER JOIN MainDatabase.dbo.sprtovar st ON ds.pnt = st.pnt
INNER JOIN MainDatabase.dbo.sprGrup sgr ON st.kodgr = sgr.kodgr
INNER JOIN MainDatabase.dbo.sprediz sediz ON st.edizid = sediz.edizid
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
LEFT OUTER JOIN technolog.dbo.tbgoodsremains gr ON --ds.pnt_as_key = gr.pnt_as_key AND
gr.pnt_as_key = goods.id AND gr.accountDateGoods = 
(SELECT MAX(gr1.accountDateGoods) FROM technolog.dbo.tbgoodsremains gr1 WHERE gr1.pnt_as_key = gr.pnt_as_key
AND gr.accountDateGoods <= ''' + CAST(@END_DATE AS VARCHAR(12))  + ''') 
WHERE 
dc.datedoc <= ''' + CAST(@END_DATE AS VARCHAR(12)) + ''' AND dc.datedoc >= ''' + CAST(@START_DATE AS VARCHAR(12)) 
--+  '''  AND st.pnt IN (' + @CODES_GOODS + ')' 
+  '''  AND ds.pnt_as_key IN (' + @CODES_GOODS + ')' 
+  ' AND dc.kodskl = '  + CAST(@CODE_WAREHOUSE AS VARCHAR(4))
EXEC (@SQL_TEXT)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.ListBySubGroupsReport
@CODES_GROUPS VARCHAR(200),
@CODES_SUBGROUPS VARCHAR(200),
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
DECLARE @SQL_TEXT VARCHAR(5000)
--MUST BE REWRITTEN
SET @SQL_TEXT =
'SELECT DISTINCT sgr.namegr AS namegr, ds.pnt_as_key,goods.namet,goods.sort,goods.vlajn,goods.jirn,sediz.ediz AS ediz, 0 as kolf, 0 as ceno,
COALESCE(NULLIF(gr.remains,NULL),0) remains, 
COALESCE(NULLIF(gr.avr_price,NULL),0) price, gr.accountDateGoods
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
INNER JOIN MainDatabase.dbo.sprtovar st ON ds.pnt = st.pnt
INNER JOIN MainDatabase.dbo.sprGrup sgr ON st.kodgr = sgr.kodgr
INNER JOIN MainDatabase.dbo.sprediz sediz ON st.edizid = sediz.edizid
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
LEFT OUTER JOIN technolog.dbo.tbgoodsremains gr ON --ds.pnt_as_key = gr.pnt_as_key AND
gr.pnt_as_key = goods.id AND gr.accountDateGoods =
( SELECT max(gr1.accountDateGoods) FROM technolog.dbo.tbgoodsremains gr1 WHERE gr1.pnt_as_key = gr.pnt_as_key AND gr.accountDateGoods <= ''' + CAST(@END_DATE AS VARCHAR(12))  + ''')
WHERE dc.datedoc <= ''' + CAST(@END_DATE AS VARCHAR(12)) + ''' AND dc.datedoc >= ''' + CAST(@START_DATE AS VARCHAR(12)) +
+  '''  AND st.kodgr in (' + @CODES_GROUPS + ') AND st.kodpgr IN (' + @CODES_SUBGROUPS + ')' 
+  ' AND dc.kodskl = '  + CAST(@CODE_WAREHOUSE AS VARCHAR(4)) 
EXEC (@SQL_TEXT)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.ListByAssortmentReport
@CODES_GROUPS VARCHAR(200),
@CODES_SUBGROUPS VARCHAR(200),
@CODES_ASSORTMENT VARCHAR(200),
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
DECLARE @SQL_TEXT VARCHAR(5000)
--MUST BE REWRITTEN
SET @SQL_TEXT =
'SELECT DISTINCT sgr.namegr AS namegr, ds.pnt_as_key,goods.namet,goods.sort,goods.vlajn,goods.jirn,sediz.ediz AS ediz, 0 as kolf, 0 as ceno,
COALESCE(NULLIF(gr.remains,NULL),0) remains, 
COALESCE(NULLIF(gr.avr_price,NULL),0) price, gr.accountDateGoods
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
INNER JOIN MainDatabase.dbo.sprtovar st ON ds.pnt = st.pnt
INNER JOIN MainDatabase.dbo.sprGrup sgr ON st.kodgr = sgr.kodgr
INNER JOIN MainDatabase.dbo.sprediz sediz ON st.edizid = sediz.edizid
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
LEFT OUTER JOIN technolog.dbo.tbgoodsremains gr ON --ds.pnt_as_key = gr.pnt_as_key AND
gr.pnt_as_key = goods.id AND gr.accountDateGoods = 
(SELECT MAX(gr1.accountDateGoods) FROM technolog.dbo.tbgoodsremains gr1 WHERE gr1.pnt_as_key = gr.pnt_as_key
AND gr.accountDateGoods <= ''' + CAST(@END_DATE AS VARCHAR(12))  + ''') 
WHERE 
dc.datedoc <= ''' + CAST(@END_DATE AS VARCHAR(12)) + ''' AND dc.datedoc >= ''' + CAST(@START_DATE AS VARCHAR(12)) 
+ '''  AND st.kodgr in (' + @CODES_GROUPS + ') AND st.kodpgr IN ( ' + @CODES_SUBGROUPS + ' ) '  
+ ' AND st.kodvid IN ( ' + @CODES_ASSORTMENT + ' ) '  +  ' AND dc.kodskl = '  + CAST(@CODE_WAREHOUSE AS VARCHAR(4))
--print @SQL_TEXT
EXEC (@SQL_TEXT)



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ListArrivedGoodsBySubGroupsReport
@CODES_GROUPS VARCHAR(200),
@CODES_SUBGROUPS VARCHAR(200),
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
DECLARE  @CODE_ARRIVED_OUT INT
SELECT @CODE_ARRIVED_OUT = ARRIVED_OUT FROM technolog.dbo.gropersettings
DECLARE @SQL_TEXT VARCHAR(5000)
SET @SQL_TEXT =
'SELECT sgr.namegr,ds.pnt_as_key,RTRIM(goods.namet) + '' '' + COALESCE(NULLIF(goods.sort,''б/с''),'''')  + '' '' 
+ COALESCE(NULLIF(CAST(goods.vlajn AS VARCHAR(12)),''0.00''),'''') 
+ COALESCE(NULLIF(CAST(goods.jirn AS VARCHAR(12)),''0.00''),'''')  AS namet,
sediz.ediz,ds.kolf,ds.ceno,technolog.dbo.CostRawMaterialArrived(ds.idstr)  AS total 
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
INNER JOIN MainDatabase.dbo.sprtovar st ON ds.pnt = st.pnt
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
INNER JOIN MainDatabase.dbo.sprGrup sgr ON st.kodgr = sgr.kodgr
INNER JOIN MainDatabase.dbo.sprediz sediz ON st.edizid = sediz.edizid
WHERE dc.viddoc = 1 AND 
dc.datedoc <= ''' + CAST(@END_DATE AS VARCHAR(12)) + 
''' AND dc.datedoc >= ''' + CAST(@START_DATE AS VARCHAR(12)) + '''  AND st.kodgr in (' 
+ @CODES_GROUPS + ') AND st.kodpgr IN (' + @CODES_SUBGROUPS + ')' 
+ ' AND dc.kodskl = ' + CAST(@CODE_WAREHOUSE AS VARCHAR(4)) 
+ ' AND dc.idgroper = ' + CAST(@CODE_ARRIVED_OUT AS VARCHAR(4))
EXEC (@SQL_TEXT)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ListArrivedGoodsByGroupsReport
@CODES_GROUPS VARCHAR(200),
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
DECLARE @SQL_TEXT VARCHAR(5000)
--MUST BE REWRITTEN
DECLARE  @CODE_ARRIVED_OUT INT
SELECT @CODE_ARRIVED_OUT = ARRIVED_OUT FROM technolog.dbo.gropersettings
SET @SQL_TEXT =
'SELECT sgr.namegr,ds.pnt_as_key,RTRIM(goods.namet) + '' '' + COALESCE(NULLIF(goods.sort,''б/с''),'''')  + '' '' 
+ COALESCE(NULLIF(CAST(goods.vlajn AS VARCHAR(12)),''0.00''),'''') 
+ COALESCE(NULLIF(CAST(goods.jirn AS VARCHAR(12)),''0.00''),'''')  AS namet,
sediz.ediz,ds.kolf,ds.ceno,technolog.dbo.CostRawMaterialArrived(ds.idstr)  AS total 
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
INNER JOIN MainDatabase.dbo.sprtovar st ON ds.pnt = st.pnt
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
INNER JOIN MainDatabase.dbo.sprGrup sgr ON st.kodgr = sgr.kodgr
INNER JOIN MainDatabase.dbo.sprediz sediz ON st.edizid = sediz.edizid
WHERE dc.viddoc = 1 AND sgr.kodgr IN ( ' + @CODES_GROUPS + ' ) AND 
dc.datedoc <= ''' + CAST(@END_DATE AS VARCHAR(12)) + ''' AND dc.datedoc >= ''' +
CAST(@START_DATE AS VARCHAR(12)) +
+ '''  AND st.kodgr in (' + @CODES_GROUPS + ')'
+  ' AND dc.kodskl = ' + CAST(@CODE_WAREHOUSE AS VARCHAR(4)) 
+ ' AND dc.idgroper = ' + CAST(@CODE_ARRIVED_OUT AS VARCHAR(4))
EXEC (@SQL_TEXT)
--print @SQL_TEXT

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ListByAllGoodsReport
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
SELECT DISTINCT sgr.namegr AS namegr, ds.pnt_as_key, goods.namet, goods.sort, goods.vlajn, goods.jirn, sediz.ediz AS ediz, 0 as kolf, 0 as ceno,
COALESCE(NULLIF(gr.remains,NULL),0) remains, 
COALESCE(NULLIF(gr.avr_price,NULL),0) price, gr.accountDateGoods
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
INNER JOIN MainDatabase.dbo.sprtovar st ON ds.pnt = st.pnt
INNER JOIN MainDatabase.dbo.sprGrup sgr ON st.kodgr = sgr.kodgr
INNER JOIN MainDatabase.dbo.sprediz sediz ON st.edizid = sediz.edizid
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
LEFT OUTER JOIN technolog.dbo.tbgoodsremains gr ON --ds.pnt_as_key = gr.pnt_as_key AND
gr.pnt_as_key = goods.id AND gr.accountDateGoods = (SELECT MAX(gr1.accountDateGoods) FROM technolog.dbo.tbgoodsremains gr1
WHERE gr1.pnt_as_key = gr.pnt_as_key AND gr1.accountDateGoods <= @END_DATE)
WHERE dc.datedoc <= @END_DATE and dc.datedoc >= @START_DATE  AND dc.kodskl = @CODE_WAREHOUSE


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.CreateListGoodsReport
@CODES_GROUPS VARCHAR(200),
@CODES_SUBGR VARCHAR(200),
@CODES_ASSORTMENT VARCHAR(200),
@CODES_GOODS VARCHAR(200),
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
IF ( @CODES_GROUPS <> '' AND @CODES_SUBGR = '' AND @CODES_ASSORTMENT = '')
BEGIN
  -- return data for creating report by groups 	
  EXEC dbo.ListByGroupsReport @CODES_GROUPS, @START_DATE, @END_DATE, @CODE_WAREHOUSE
END
IF ( @CODES_GROUPS <> '' AND @CODES_SUBGR <> '' AND @CODES_ASSORTMENT = '')
BEGIN
  -- return data for creating report by subgroups 	
  EXEC dbo.ListBySubGroupsReport @CODES_GROUPS,@CODES_SUBGR, @START_DATE, @END_DATE, @CODE_WAREHOUSE
END
IF ( @CODES_GROUPS <> '' AND @CODES_SUBGR <> '' AND @CODES_ASSORTMENT <> '' AND @CODES_GOODS = '' )
BEGIN
  -- return data for creating report by assortment	
  EXEC dbo.ListByAssortmentReport @CODES_GROUPS,@CODES_SUBGR,@CODES_ASSORTMENT, @START_DATE, @END_DATE,
  @CODE_WAREHOUSE
END
IF ( @CODES_GROUPS = '' AND @CODES_SUBGR = '' AND @CODES_ASSORTMENT = '' AND @CODES_GOODS <> '')
BEGIN
-- return data for creating report by selected goods	
  EXEC dbo.ListBySelectedGoodsReport  @CODES_GOODS,@START_DATE, @END_DATE,@CODE_WAREHOUSE
END
IF ( @CODES_GROUPS = '' AND @CODES_SUBGR = '' AND @CODES_ASSORTMENT = '' AND @CODES_GOODS = ''  )
BEGIN
  EXEC dbo.ListByAllGoodsReport @START_DATE, @END_DATE,@CODE_WAREHOUSE
END
IF ( @CODES_GROUPS <> '' AND @CODES_SUBGR <> '' AND @CODES_ASSORTMENT <> '' AND @CODES_GOODS <> '' )
BEGIN
  -- return data for creating report by selected goods	
  EXEC dbo.ListBySelectedGoodsReport  @CODES_GOODS,@START_DATE, @END_DATE,@CODE_WAREHOUSE
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ListArrivedGoodsByAssortmentReport
@CODES_GROUPS VARCHAR(200),
@CODES_SUBGROUPS VARCHAR(200),
@CODES_ASSORTMENT VARCHAR(200),
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
DECLARE @SQL_TEXT VARCHAR(5000)
--MUST BE REWRITTEN
DECLARE  @CODE_ARRIVED_OUT INT
SELECT @CODE_ARRIVED_OUT = ARRIVED_OUT FROM technolog.dbo.gropersettings
SET @SQL_TEXT =  
'SELECT sgr.namegr,ds.pnt_as_key,RTRIM(goods.namet) + '' '' + COALESCE(NULLIF(goods.sort,''б/с''),'''')  + '' '' 
+ COALESCE(NULLIF(CAST(goods.vlajn AS VARCHAR(12)),''0.00''),'''') 
+ COALESCE(NULLIF(CAST(goods.jirn AS VARCHAR(12)),''0.00''),'''')  AS namet,
sediz.ediz,ds.kolf,ds.ceno,technolog.dbo.CostRawMaterialArrived(ds.idstr)  AS total 
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
INNER JOIN MainDatabase.dbo.sprtovar st ON ds.pnt = st.pnt
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
INNER JOIN MainDatabase.dbo.sprGrup sgr ON st.kodgr = sgr.kodgr
INNER JOIN MainDatabase.dbo.sprediz sediz ON st.edizid = sediz.edizid
WHERE dc.viddoc = 1 AND 
dc.datedoc <= ''' + CAST(@END_DATE AS VARCHAR(12)) + ''' AND dc.datedoc >= ''' + CAST(@START_DATE AS VARCHAR(12)) 
+ ''' AND dc.kodskl = ' + CAST(@CODE_WAREHOUSE AS VARCHAR(4)) +
+ '  AND st.kodgr in (' + @CODES_GROUPS + ') AND st.kodpgr IN ( ' + @CODES_SUBGROUPS + ' ) '  + ' AND st.kodvid IN ( ' + @CODES_ASSORTMENT + ' ) ' 
+ ' AND dc.idgroper = ' + CAST(@CODE_ARRIVED_OUT AS VARCHAR(4))
--print @SQL_TEXT
EXEC (@SQL_TEXT)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ListArrivedGoodsBySelectedGoodsReport
@CODES_GOODS VARCHAR(200),
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
DECLARE @SQL_TEXT VARCHAR(5000)
--MUST BE REWRITTEN
-- 06.06.2006 (ds.kolf*ds.ceno) AS total was changed to technolog.dbo.CostRawMaterialArrived(ds.idstr) AS total
DECLARE  @CODE_ARRIVED_OUT INT
SELECT @CODE_ARRIVED_OUT = ARRIVED_OUT FROM technolog.dbo.gropersettings
SET @SQL_TEXT = 
'SELECT sgr.namegr,ds.pnt_as_key,RTRIM(goods.namet) + '' '' + COALESCE(NULLIF(goods.sort,''б/с''),'''')  + '' '' 
+ COALESCE(NULLIF(CAST(goods.vlajn AS VARCHAR(12)),''0.00''),'''') 
+ COALESCE(NULLIF(CAST(goods.jirn AS VARCHAR(12)),''0.00''),'''')  AS namet,
sediz.ediz,ds.kolf,ds.ceno,technolog.dbo.CostRawMaterialArrived(ds.idstr) AS total 
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
INNER JOIN MainDatabase.dbo.sprtovar st ON ds.pnt = st.pnt
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
INNER JOIN MainDatabase.dbo.sprGrup sgr ON st.kodgr = sgr.kodgr
INNER JOIN MainDatabase.dbo.sprediz sediz ON st.edizid = sediz.edizid
WHERE dc.viddoc = 1 AND 
dc.datedoc <= ''' + CAST(@END_DATE AS VARCHAR(12)) 
+ ''' AND dc.datedoc >= ''' + CAST(@START_DATE AS VARCHAR(12)) 
--+ '''  AND st.pnt IN (' + @CODES_GOODS + ')' 
+ '''  AND ds.pnt_as_key IN (' + @CODES_GOODS + ')' 
--+ '''  AND ds.pnt IN (' + @CODES_GOODS + ')' 
+ ' AND dc.kodskl = ' + CAST(@CODE_WAREHOUSE AS VARCHAR(4))
+ 'AND dc.idgroper = ' + CAST(@CODE_ARRIVED_OUT AS VARCHAR(4))
EXEC (@SQL_TEXT)
--print @SQL_TEXT


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.ListAllArrivedGoods
@START_DATE datetime,
@END_DATE datetime,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
DECLARE  @CODE_ARRIVED_OUT INT
SELECT @CODE_ARRIVED_OUT = ARRIVED_OUT FROM technolog.dbo.gropersettings
SELECT sgr.namegr,ds.pnt_as_key, RTRIM(goods.namet) + ' ' + COALESCE(NULLIF(goods.sort,'б/с'),'')  + ' ' 
+ COALESCE(NULLIF(CAST(goods.vlajn AS VARCHAR(12)),'0.00'),'') + COALESCE(NULLIF(CAST(goods.jirn AS VARCHAR(12)),'0.00'),'')  AS namet,
sediz.ediz,ds.kolf,ds.ceno,technolog.dbo.CostRawMaterialArrived(ds.idstr) AS total, dc.datedoc 
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
INNER JOIN MainDatabase.dbo.sprtovar st ON ds.pnt = st.pnt
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
INNER JOIN MainDatabase.dbo.sprGrup sgr ON st.kodgr = sgr.kodgr
INNER JOIN MainDatabase.dbo.sprediz sediz ON st.edizid = sediz.edizid
WHERE dc.datedoc <= @END_DATE and dc.datedoc >= @START_DATE and dc.viddoc = 1
AND dc.kodskl = @CODE_WAREHOUSE AND dc.idgroper = @CODE_ARRIVED_OUT
--Commented 05/06/2006
--DECLARE  @CODE_ARRIVED_OUT INT
--SELECT @CODE_ARRIVED_OUT = ARRIVED_OUT FROM technolog.dbo.gropersettings
--SELECT sgr.namegr,ds.pnt_as_key, RTRIM(goods.namet) + ' ' + COALESCE(NULLIF(goods.sort,'б/с'),'')  + ' ' 
--+ COALESCE(NULLIF(CAST(goods.vlajn AS VARCHAR(12)),'0.00'),'') + COALESCE(NULLIF(CAST(goods.jirn AS VARCHAR(12)),'0.00'),'')  AS namet,
--sediz.ediz,ds.kolf,ds.ceno,(ds.kolf*ds.ceno) AS total, dc.datedoc 
--FROM MainDatabase.dbo.docstring ds
--INNER JOIN MainDatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
--INNER JOIN MainDatabase.dbo.sprtovar st ON ds.pnt = st.pnt
--INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
--INNER JOIN MainDatabase.dbo.sprGrup sgr ON st.kodgr = sgr.kodgr
--INNER JOIN MainDatabase.dbo.sprediz sediz ON st.edizid = sediz.edizid
--WHERE dc.datedoc <= @END_DATE and dc.datedoc >= @START_DATE and dc.viddoc = 1
--AND dc.kodskl = @CODE_WAREHOUSE AND dc.idgroper = @CODE_ARRIVED_OUT

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.CreateListArrivedGoodsReport
@CODES_GROUPS VARCHAR(200),
@CODES_SUBGR VARCHAR(200),
@CODES_ASSORTMENT VARCHAR(200),
@CODES_GOODS VARCHAR(200),
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
IF ( @CODES_GROUPS <> '' AND @CODES_SUBGR = '' AND @CODES_ASSORTMENT = '')
BEGIN
  -- return data for creating report by groups 	
  EXEC dbo.ListArrivedGoodsByGroupsReport @CODES_GROUPS, @START_DATE, @END_DATE,@CODE_WAREHOUSE
END
IF ( @CODES_GROUPS <> '' AND @CODES_SUBGR <> '' AND @CODES_ASSORTMENT = '')
BEGIN
  -- return data for creating report by subgroups 	
  EXEC dbo.ListArrivedGoodsBySubGroupsReport @CODES_GROUPS,@CODES_SUBGR, @START_DATE, @END_DATE,
  @CODE_WAREHOUSE
END
IF ( @CODES_GROUPS <> '' AND @CODES_SUBGR <> '' AND @CODES_ASSORTMENT <> '' AND @CODES_GOODS = '' )
BEGIN
  -- return data for creating report by assortment	
  EXEC dbo.ListArrivedGoodsByAssortmentReport @CODES_GROUPS,@CODES_SUBGR,@CODES_ASSORTMENT, 
  @START_DATE, @END_DATE,@CODE_WAREHOUSE
END
--IF ( @CODES_GROUPS = '' AND @CODES_SUBGR = '' AND @CODES_ASSORTMENT = '' AND @CODES_GOODS <> '')
--BEGIN
-- return data for creating report by selected goods	
--  EXEC dbo.ListBySelectedGoodsReport  @CODES_GOODS,@START_DATE, @END_DATE
--END
IF ( @CODES_GROUPS = '' AND @CODES_SUBGR = '' AND @CODES_ASSORTMENT = '' AND @CODES_GOODS = ''  )
BEGIN
  EXEC dbo.ListAllArrivedGoods @START_DATE, @END_DATE,@CODE_WAREHOUSE
END
IF ( @CODES_GROUPS <> '' AND @CODES_SUBGR <> '' AND @CODES_ASSORTMENT <> '' AND @CODES_GOODS <> '' )
BEGIN
  -- return data for creating report by selected goods	
  EXEC dbo.ListArrivedGoodsBySelectedGoodsReport  @CODES_GOODS,@START_DATE, @END_DATE,@CODE_WAREHOUSE
END




SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.FindDogovor
@idPredpr smallint,
@Dogovor varchar(30) output
AS
select @Dogovor=ISNULL(Dogovor,'') from maindatabase.dbo.tbPredpr
-- where idPredpr=(Select IdPlat from tbPredpr where IdPredpr=@IdPredpr and IdPlat is not null)
 where idPredpr=(Select ISNULL(IdPlat,@IdPredpr) from maindatabase.dbo.tbPredpr where IdPredpr=@IdPredpr)
Return

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.FindFlO
@idPredpr smallint,
@FioDir varchar(30) output,
@FIOGlBuh varchar(30) output
 AS
select @FIODir=FioDir,@FIOGlBuh=FIOGlBuh from maindatabase.dbo.tbPredpr
 where idPredpr=@idPredpr

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.FindIdOper
@NameGrOper char(50),
@VidDoc tinyint
 AS
 if @VidDoc=2 or @VidDoc=3
Select IdGrOper from tbGrOper
where NameGrOper=@NameGrOper and IdNameDeist=(Select IdNameDeist from maindatabase.dbo.tbDeist where NameDeist='Выбытие'
and IdDeistPar=(Select IdNameDeist from maindatabase.dbo.tbDeist where NameDeist='АРМ товароведа'))
 else
Select IdGrOper from tbGrOper
where NameGrOper=@NameGrOper and IdNameDeist=(Select IdNameDeist from maindatabase.dbo.tbDeist where NameDeist='Поступление'
and IdDeistPar=(Select IdNameDeist from maindatabase.dbo.tbDeist where NameDeist='АРМ товароведа'))

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.FindIdOperN
@NameGrOper char(50),
@VidDoc tinyint,
@IdGrOper smallint out
 AS
 if @VidDoc=1 or @VidDoc=5
Select  @IdGrOper=IdGrOper from tbGrOper
where NameGrOper=@NameGrOper and IdNameDeist=(Select IdNameDeist from maindatabase.dbo.tbDeist where NameDeist='Поступление'
and IdDeistPar=(Select IdNameDeist from maindatabase.dbo.tbDeist where NameDeist='АРМ товароведа'))
--Select  IdGrOper from tbGrOperN where  NameGrOper=@NameGrOper and IdNameDeist=1 and IdPar=
--                                                                (Select IdGrOper from tbGrOperN where NameGrOper='Поступление')
 else
Select @IdGrOper=IdGrOper from tbGrOper
where NameGrOper=@NameGrOper and IdNameDeist=(Select IdNameDeist from maindatabase.dbo.tbDeist where NameDeist='Выбытие'
and IdDeistPar=(Select IdNameDeist from maindatabase.dbo.tbDeist where NameDeist='АРМ товароведа'))

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.FindIdOperNN
@NameGrOper char(50),
@VidDoc tinyint,
@OsnSch Varchar(10)
 AS
declare @VDoc varchar(8)
 if @VidDoc=2 or @VidDoc=3
 set @Vdoc='%Расход%'
else
 set @Vdoc='%Приход%'
Select IdGrOper from tbGrOper tbG where (Select (Case When CharIndex(' ',NameDeist)=0 then ''
  else
  SubString(NameDeist,1,CharIndex(' ',NameDeist)-1) end)
   from tbDeist where IdNameDeist=(Select IdDeistPar from tbDeist 
where IdNameDeist=tbG.IdNameDeist) and IdDeistPar=2)  like @OsnSch 
and (Select NameDeist from  tbDeist where IdNameDeist=tbG.IdNameDeist) like @Vdoc 
and nameGrOper=@NameGrOper

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.FindIdOperNNN
@NameGrOper char(50),
@VidDoc tinyint,
@OsnSch Varchar(10),
@idGrOper smallint out
 AS
declare @VDoc varchar(8)
 if @VidDoc=2 or @VidDoc=3
 set @Vdoc='%Расход%'
else
 set @Vdoc='%Приход%'
Select @IdGrOper=IdGrOper from tbGrOper tbG where (Select (Case When CharIndex(' ',NameDeist)=0 then ''
  else
  SubString(NameDeist,1,CharIndex(' ',NameDeist)-1) end)
   from tbDeist where IdNameDeist=(Select IdDeistPar from tbDeist 
where IdNameDeist=tbG.IdNameDeist) and IdDeistPar=2)  like @OsnSch 
and (Select NameDeist from  tbDeist where IdNameDeist=tbG.IdNameDeist) like @Vdoc 
and nameGrOper=@NameGrOper

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.FindKgr 
 @NameNode char (30),
  @KodGr [tinyint] output
 AS
Select @Kodgr=kodGr from SprGrup where NameGr=@NameNode
Return

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.FindKgrKPgr 
 @NameNode char (30),
 @KodGr [tinyint] output,
 @KodPgr [tinyint] output
 AS
Select @Kodgr=kodGr,@KodPgr=KodPgr from SprPGrup where NamePGr=@NameNode
Return

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.FindNamePredpr
@idPredpr smallint,
@NamePredprShort varchar(50) output
AS
select @NamePredprShort=NamePredprShort from maindatabase.dbo.tbPredpr
 where idPredpr=@idPredpr
Return

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.FindNameTown
@idPredpr smallint,
@NameTown varchar(25) output
 AS
select @NameTown=NameTown from maindatabase.dbo.tbTown
 where idTown=(select idTown from maindatabase.dbo.tbPredpr
                            where idPredpr=@idPredpr)
   and idRaion=(select idRaion from maindatabase.dbo.tbPredpr
                            where idPredpr=@idPredpr)
Return

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].FindPhoneFaxPredpr
@idPredpr int,
@Phone varchar(30) output,
@Fax varchar(30) output
 AS
select  @Phone=Phone, @Fax=Fax from maindatabase.dbo.tbPredpr
 where idPredpr=@IdPredpr 
return

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.FindRekvizPlat  
@idPredpr smallint, 
@UNN varchar(20) output,
@KodOKPO  varchar(20) output,
@LIC varchar(50) output,
@idPlat smallint output
AS
Select @IdPlat=Isnull(IdPlat,@IdPredpr) from maindatabase.dbo.tbPredpr where IdPredpr=@IdPredpr
select @UNN=UNN, @KodOKPO=KodOKPO,@LIC=LIC,
          @idPlat=idPredpr  from maindatabase.dbo.tbPredpr
 where idPredpr=@IdPlat

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.FindRschetPlat
@idPredpr smallint,
@Rschet varchar(30) output,
@idBank smallint output,
@KodMFO varchar(20)  output
 AS
set @Rschet=''
set @KodMFO=''
select @Rschet=Rschet,@idBank=idBank from maindatabase.dbo.tbRschet
 where osn=1 and idPredpr=ISNULL((select idPlat from maindatabase.dbo.tbPredpr
                                              where idPredpr=@idPredpr),@idPredpr) 
select @KodMFO=KodMFO from maindatabase.dbo.tbPredpr where IdPredpr=@IdBank
Return

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.FindSchet
@Sc Integer,
@SubSc Integer,
@OutKod Integer output
 AS
if Exists(Select kodSchet, kodSubSchet From maindatabase.dbo.tbSprSchet Where kodSchet = @Sc AND kodSubSchet = @SubSc)
Select @OutKod = 1
ELSE
Select @OutKod = 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.FindStHoFl
@idPredpr smallint,
@StHoFl varchar(30) output
 AS
select @StHoFl=StHoFl from maindatabase.dbo.tbPredpr
 where idPredpr=@idPredpr

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE FioKassir 
@Fio VarChar(50),
@f varchar(50) output
 AS
 Select @f  = Fio From MainDataBase.dbo.SPR_WORKS Where TabN = (select TabN from Buh.dbo.tbSprAPrizKassa where idSchetSubSchet = @Fio )

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  PROCEDURE dbo.GetGoodsForReportTree
@CODE_GROUP int,
@CODE_SUBGROUP int,
@CODE_ASSORTMENT int,
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
DECLARE @SQL_TEXT VARCHAR(5000) 
SET @SQL_TEXT = 
-- 'ds.pnt_as_key AS' pnt1 was deleted
'SELECT DISTINCT goods.code_gr AS code_gr,goods.code_subgr as code_subgr,
goods.code_assort as code_assortment, ds.pnt_as_key AS pnt, goods.namet as namet, 
CASE goods.sort WHEN ''б/с'' THEN '''' ELSE goods.sort END AS sort, goods.vlajn AS vlajn,goods.jirn AS jirn,
COALESCE(NULLIF(gr.remains,NULL),0) remains, 
COALESCE(NULLIF(gr.avr_price,NULL),0) price, gr.accountDateGoods
FROM Maindatabase.dbo.docstring ds 
INNER JOIN Maindatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc AND
dc.datedoc <= ''' + CAST(@END_DATE AS VARCHAR(12)) + 
''' AND dc.datedoc >= ''' + CAST(@START_DATE AS VARCHAR(12)) 
+'''' + ' AND dc.kodskl = ' + CAST(@CODE_WAREHOUSE AS VARCHAR(4))
--EXISTS ( SELECT id from technolog.dbo.tbgoods )  
+ ' INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id' 
IF @CODE_GROUP > 0
BEGIN
 SET @SQL_TEXT =  @SQL_TEXT  + ' AND goods.code_gr = ' + CAST( @CODE_GROUP AS VARCHAR(3) )
END 
IF @CODE_SUBGROUP > 0
BEGIN
 SET @SQL_TEXT =  @SQL_TEXT  + ' AND goods.code_subgr = ' + CAST( @CODE_SUBGROUP AS VARCHAR(3) )
END 
IF @CODE_ASSORTMENT > 0
BEGIN
 SET @SQL_TEXT =  @SQL_TEXT  + ' AND goods.codeassort = ' + CAST(@CODE_ASSORTMENT AS VARCHAR(3) ) 
END 
SET @SQL_TEXT =  @SQL_TEXT  + ' LEFT OUTER JOIN technolog.dbo.tbgoodsremains gr ON 
ds.pnt_as_key = gr.pnt_as_key AND gr.pnt_as_key = goods.id 
AND gr.accountDateGoods = ( SELECT max(gr1.accountDateGoods) FROM technolog.dbo.tbgoodsremains gr1 
INNER JOIN Maindatabase.dbo.tbsort sort ON ( goods.idsort = sort.idsort OR goods.idsort IS NULL)
WHERE gr1.pnt_as_key = gr.pnt_as_key AND gr1.accountDateGoods <= ''' + CAST(@END_DATE AS VARCHAR(12)) + ''')'
EXEC (@SQL_TEXT)
--print @SQL_TEXT


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.InsUpdDocOfAccount 
@IdDoc int,
@NumOtch int,
@DateOtch datetime,
@TabN int
AS
  update maindatabase.dbo.DocCaption
       set NumOtch=@NumOtch,
             DateOtch=@DateOtch,
            TabN=@TabN
  where (IdDoc=@IdDoc)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[InvoiceArrivalReport] 
@ID_DOC INT,
@ID_ENTERPR_SENDER INT,
@ID_ENTERPR_RECIPIENT INT
--@ID_OPER INT OUTPUT
AS 
-- Sender
SELECT  v1.skladname,v1.stockNamePredprShort,v1.nametown,v1.zipcode, v1.StHoFl ,
ISNULL(rschet.rschet,'') AS rschet, ISNULL(pr2.kodmfo,'') AS kodmfo,
v1.idpredpr,v1.idbank,ISNULL(pr2.NamePredprshort,'') AS bankNamePredpr,v1.oper,v1.FIODir,v1.kodmfo,
pr3.dogovor,pr3.unn AS stockUnn, pr3.KodOKPO AS stockKodOKPO, pr3.lic AS stockLic,pr3.idplat,v1.idpredprAccount
FROM 
(
SELECT v.skladname,v.stockNamePredprShort, v.zipcode ,v.nametown,v.StHoFl,
v.idpredpr,v.idbank,v.oper,v.FIODir,v.kodmfo,v.idplat,v.idpredprAccount
FROM
(
SELECT ISNULL(pr.namePredprShort,'')  AS skladname,dc.idpredpr,pr.idpredpr AS idpredprAccount,
CASE WHEN pr.idplat = @ID_ENTERPR_SENDER THEN pr.namePredprShort 
ELSE (SELECT namePredprShort FROM maindatabase.dbo.tbpredpr WHERE idpredpr = pr.idplat)  END AS stockNamePredprShort,
ISNULL(CAST(pr.zipcode AS VARCHAR(10)),'') AS zipcode, ISNULL(town.nametown,'') AS nametown, ISNULL(pr.StHoFl,'') AS StHoFl,
oper.namegroper AS oper,ISNULL(pr.FIODir,'') AS FIODir,pr.kodmfo,
CASE WHEN pr.idplat = @ID_ENTERPR_SENDER THEN pr.idpredpr
ELSE (SELECT idpredpr FROM maindatabase.dbo.tbpredpr WHERE idpredpr = pr.idplat)  END AS idplat,
CASE WHEN pr.idplat = @ID_ENTERPR_SENDER THEN 
(SELECT DISTINCT idbank FROM maindatabase.dbo.tbRschet WHERE idpredpr =  @ID_ENTERPR_SENDER AND osn = 1)
ELSE (SELECT DISTINCT idbank FROM maindatabase.dbo.tbRschet WHERE idpredpr = pr.idplat AND osn = 1)  END AS idbank
FROM maindatabase.dbo.doccaption dc
INNER JOIN maindatabase.dbo.tbpredpr pr ON dc.idpredpr = pr.idpredpr 
AND dc.idpredpr = @ID_ENTERPR_SENDER AND dc.iddoc = @ID_DOC
LEFT OUTER JOIN maindatabase.dbo.tbtown town ON pr.idtown = town.idtown
INNER JOIN maindatabase.dbo.tbgroper oper ON oper.idgroper = dc.idgroper
) v
) v1
LEFT OUTER JOIN maindatabase.dbo.tbpredpr pr3 ON pr3.idpredpr = v1.idplat--v1.idpredprAccount --v1.idpredpr
LEFT OUTER JOIN maindatabase.dbo.tbpredpr pr2 ON pr2.idpredpr = v1.idbank
LEFT OUTER JOIN maindatabase.dbo.tbrschet rschet ON rschet.idpredpr = v1.idplat--v1.idpredprAccount--v1.idpredpr
AND rschet.idBank= v1.idbank AND osn = 1

-- Receiver
SELECT v1.enterprName,v1.zipcode,v1.nametown, v1.StHoFl,v1.stockNamePredprShort, ISNULL(rschet.rschet,'') AS  rschet, ISNULL(pr2.kodmfo,'') AS kodmfo,
pr3.dogovor,
v1.idpredpr,v1.idbank,ISNULL(pr2.NamePredprshort,'') AS bankNamePredpr,
pr3.unn AS enterprUnn, pr3.KodOKPO AS enterprKodOKPO, pr3.lic AS enterprLic,pr3.idplat--,v1.idpredprAccount
FROM 
(
SELECT v.enterprName, v.zipcode,v.nametown, v.StHoFl,v.stockNamePredprShort,
v.idpredpr,v.idbank,v.idplat--,v.idpredprAccount
FROM
(
SELECT  ISNULL(pr.namePredprShort,'')  AS enterprName,dc.idpredpr,
CASE WHEN pr.idplat = @ID_ENTERPR_RECIPIENT THEN pr.namePredprShort 
ELSE (SELECT namePredprShort FROM maindatabase.dbo.tbpredpr WHERE idpredpr = pr.idplat)  END AS stockNamePredprShort,
ISNULL(CAST(pr.zipcode AS VARCHAR(10)),'') AS zipcode, ISNULL(town.nametown,'') AS nametown,ISNULL(pr.StHoFl,'') AS StHoFl,
CASE WHEN pr.idplat = @ID_ENTERPR_RECIPIENT THEN pr.idpredpr
ELSE (SELECT idpredpr FROM maindatabase.dbo.tbpredpr WHERE idpredpr = pr.idplat)  END AS idplat,
CASE WHEN pr.idplat = @ID_ENTERPR_RECIPIENT THEN 
(SELECT idbank FROM maindatabase.dbo.tbRschet WHERE idpredpr = 4 AND osn = 1)
ELSE (SELECT DISTINCT idbank FROM maindatabase.dbo.tbRschet WHERE idpredpr = idplat AND osn = 1)  END AS idbank
FROM maindatabase.dbo.doccaption dc
INNER JOIN maindatabase.dbo.tbpredpr pr ON dc.kodskl = @ID_ENTERPR_RECIPIENT AND dc.iddoc = @ID_DOC AND pr.idpredpr = @ID_ENTERPR_RECIPIENT
LEFT OUTER JOIN maindatabase.dbo.tbtown town ON pr.idtown = town.idtown
) v
) v1
INNER JOIN maindatabase.dbo.tbpredpr pr3 ON pr3.idpredpr = v1.idplat
LEFT OUTER JOIN maindatabase.dbo.tbpredpr pr2 ON pr2.idpredpr = v1.idbank
LEFT OUTER JOIN maindatabase.dbo.tbrschet rschet ON rschet.idpredpr = v1.idplat
AND rschet.idBank= v1.idbank AND osn = 1

-- Goods
DECLARE @ID_OPER INT
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
SELECT @ID_OPER = idgroper FROM MainDatabase.dbo.doccaption WHERE iddoc = @ID_DOC
IF @ID_OPER = @CODE_ARRIVED_OUT 
BEGIN
SET @ID_OPER = 1
END
ELSE
BEGIN
SET @ID_OPER = 0
END
SELECT RTRIM(goods.namet) + ' ' + ISNULL(sort.namesort,'') AS name_raw_material,
goods.vlajn, goods.jirn, country.namecountry,ediz.shortnameedizm,ds.kolf,ISNULL(ds.ceno,0) AS ceno, ISNULL(ds.cenpriobr,0) AS cenpriobr,st.vidup,st.minup,
st.art,st.sertif,pr.namePredprShort,ISNULL(ds.nds,0) AS nds,@ID_OPER AS idoper,ISNULL(ds.NalTr,0) AS NalTr, ISNULL(ds.NacOpt,0) AS NacOpt,ISNULL(ds.SkidPost,0) AS SkidPost 
FROM MainDatabase.dbo.doccaption dc
INNER JOIN MainDatabase.dbo.docstring ds ON dc.iddoc = ds.iddoc AND dc.iddoc = @ID_DOC
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
LEFT OUTER JOIN maindatabase.dbo.tbsort sort ON goods.idsort = sort.idsort
LEFT OUTER JOIN MainDatabase.dbo.sprtovar st ON st.pnt = ds.pnt
LEFT OUTER JOIN MainDatabase.dbo.tbPredpr pr ON st.idpredpr = pr.idpredpr
LEFT OUTER JOIN MainDatabase.dbo.tbCountry country ON country.idCountry = st.idCountry
LEFT OUTER JOIN MainDatabase.dbo.sprediz ediz ON ediz.edizid = goods.edizid--st.edizid
RETURN @ID_OPER
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[InvoiceReport] 
@ID_DOC INT,
@ID_ENTERPR_SENDER INT,
@ID_ENTERPR_RECIPIENT INT
AS 

-- Sender
SELECT v1.skladname,v1.stockNamePredprShort,v1.nametown,v1.zipcode, v1.StHoFl ,
ISNULL(rschet.rschet,'') AS rschet, ISNULL(pr2.kodmfo,'') AS kodmfo,
v1.idpredpr,v1.idbank,ISNULL(pr2.NamePredprshort,'') AS bankNamePredpr,v1.oper,v1.FIODir,v1.kodmfo,
pr3.dogovor,pr3.unn AS stockUnn, pr3.KodOKPO AS stockKodOKPO, pr3.lic AS stockLic,pr3.idplat
FROM 
(
SELECT v.skladname,v.stockNamePredprShort, v.zipcode ,v.nametown ,v.StHoFl,v.idpredpr,v.idbank,v.oper,v.FIODir,v.kodmfo,v.idplat
FROM
(
SELECT ISNULL(pr.namePredprShort,'')  AS skladname,dc.idpredpr,
CASE WHEN pr.idplat = @ID_ENTERPR_SENDER THEN pr.namePredprShort 
ELSE (SELECT namePredprShort FROM maindatabase.dbo.tbpredpr WHERE idpredpr = pr.idplat)  END AS stockNamePredprShort,
ISNULL(CAST(pr.zipcode AS VARCHAR(10)),'') AS zipcode, ISNULL(town.nametown,'') AS nametown, ISNULL(pr.StHoFl,'') AS StHoFl,
oper.namegroper AS oper,ISNULL(pr.FIODir,'') AS FIODir,pr.kodmfo,
CASE WHEN pr.idplat = @ID_ENTERPR_SENDER THEN pr.idpredpr
ELSE (SELECT idpredpr FROM maindatabase.dbo.tbpredpr WHERE idpredpr = pr.idplat)  END AS idplat,
CASE WHEN pr.idplat = @ID_ENTERPR_SENDER THEN 
(SELECT idbank FROM maindatabase.dbo.tbRschet WHERE idpredpr =  @ID_ENTERPR_SENDER AND osn = 1)
ELSE (SELECT idbank FROM maindatabase.dbo.tbRschet WHERE idpredpr = pr.idplat AND osn = 1)  END AS idbank
FROM maindatabase.dbo.doccaption dc
INNER JOIN maindatabase.dbo.tbpredpr pr ON dc.kodskl = pr.idpredpr 
AND dc.kodskl = @ID_ENTERPR_SENDER AND dc.iddoc = @ID_DOC
INNER JOIN maindatabase.dbo.tbtown town ON pr.idtown = town.idtown
INNER JOIN maindatabase.dbo.tbgroper oper ON oper.idgroper = dc.idgroper
) v
) v1
INNER JOIN maindatabase.dbo.tbpredpr pr3 ON pr3.idpredpr = v1.idplat --v1.idpredpr
LEFT OUTER JOIN maindatabase.dbo.tbpredpr pr2 ON pr2.idpredpr = v1.idbank
LEFT OUTER JOIN maindatabase.dbo.tbrschet rschet ON rschet.idpredpr = v1.idplat --v1.idpredpr
AND rschet.idBank= v1.idbank AND osn = 1

-- Receiver
SELECT v1.enterprName,v1.zipcode,v1.nametown, v1.StHoFl,v1.stockNamePredprShort, ISNULL(rschet.rschet,'') AS  rschet, ISNULL(pr2.kodmfo,'') AS kodmfo,
pr3.dogovor,
v1.idpredpr,v1.idbank,ISNULL(pr2.NamePredprshort,'') AS bankNamePredpr,
pr3.unn AS enterprUnn, pr3.KodOKPO AS enterprKodOKPO, pr3.lic AS enterprLic,pr3.idplat
FROM 
(
SELECT v.enterprName,v.zipcode,v.nametown,v.StHoFl,v.stockNamePredprShort,
v.idpredpr,v.idbank,v.idplat
FROM
(
SELECT  ISNULL(pr.namePredprShort,'')  AS enterprName,dc.idpredpr,
CASE WHEN pr.idplat = @ID_ENTERPR_RECIPIENT THEN pr.namePredprShort 
ELSE (SELECT namePredprShort FROM maindatabase.dbo.tbpredpr WHERE idpredpr = pr.idplat)  END AS stockNamePredprShort ,
ISNULL(CAST(pr.zipcode AS VARCHAR(10)),'') AS zipcode, ISNULL(town.nametown,'') AS nametown,ISNULL(pr.StHoFl,'') AS StHoFl,
CASE WHEN pr.idplat = @ID_ENTERPR_RECIPIENT THEN pr.idpredpr
ELSE (SELECT idpredpr FROM maindatabase.dbo.tbpredpr WHERE idpredpr = pr.idplat)  END AS idplat,
CASE WHEN pr.idplat = @ID_ENTERPR_RECIPIENT THEN 
(SELECT idbank FROM maindatabase.dbo.tbRschet WHERE idpredpr =  @ID_ENTERPR_RECIPIENT AND osn = 1)
ELSE (SELECT idbank FROM maindatabase.dbo.tbRschet WHERE idpredpr = pr.idplat AND osn = 1)  END AS idbank
FROM maindatabase.dbo.doccaption dc
INNER JOIN maindatabase.dbo.tbpredpr pr ON dc.idpredpr = pr.idpredpr 
AND dc.idpredpr = @ID_ENTERPR_RECIPIENT AND dc.iddoc = @ID_DOC
INNER JOIN maindatabase.dbo.tbtown town ON pr.idtown = town.idtown
) v
) v1
INNER JOIN maindatabase.dbo.tbpredpr pr3 ON pr3.idpredpr = v1.idplat -- v1.idpredpr
LEFT OUTER JOIN maindatabase.dbo.tbpredpr pr2 ON pr2.idpredpr = v1.idbank
LEFT OUTER JOIN maindatabase.dbo.tbrschet rschet ON rschet.idpredpr = v1.idplat --v1.idpredpr
AND rschet.idBank= v1.idbank AND osn = 1

-- Goods
SELECT RTRIM(goods.namet) + ' ' + ISNULL(sort.namesort,'') AS name_raw_material,
goods.vlajn, goods.jirn, country.namecountry,ediz.shortnameedizm,ds.kolf,ds.ceno,st.vidup,st.minup,
st.art,st.sertif,pr.namePredprShort,ds.nds 
FROM MainDatabase.dbo.doccaption dc
INNER JOIN MainDatabase.dbo.docstring ds ON dc.iddoc = ds.iddoc AND dc.iddoc = @ID_DOC
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
LEFT OUTER JOIN maindatabase.dbo.tbsort sort ON goods.idsort = sort.idsort
INNER JOIN MainDatabase.dbo.sprtovar st ON st.pnt = ds.pnt
LEFT OUTER JOIN MainDatabase.dbo.tbPredpr pr ON st.idpredpr = pr.idpredpr
LEFT OUTER JOIN MainDatabase.dbo.tbCountry country ON country.idCountry = st.idCountry
LEFT OUTER JOIN MainDatabase.dbo.sprediz ediz ON ediz.edizid = goods.edizid--st.edizid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[InvoiceTrReport] 
@ID_DOC INT,
@ID_WAREHOUSE INT,
@ID_ENTERPR_SENDER INT,
@ID_ENTERPR_RECIPIENT INT
AS 
--DECLARE @DOGOVOR VARCHAR(50)
--DECLARE @ID_PREDPR INT
-- Sender
SELECT v1.skladname,v1.stockNamePredprShort,v1.nametown,v1.zipcode, v1.StHoFl ,
ISNULL(rschet.rschet,'') AS rschet, ISNULL(pr2.kodmfo,'') AS kodmfo,
v1.idpredpr,v1.idbank,ISNULL(pr2.NamePredprshort,'') AS bankNamePredpr,v1.oper,v1.FIODir,v1.kodmfo,
pr3.dogovor,pr3.unn AS stockUnn, pr3.KodOKPO AS stockKodOKPO, pr3.lic AS stockLic,v1.StHoFlsklad,v1.zipcodesclad
FROM
(
SELECT v.skladname,v.stockNamePredprShort, v.zipcode ,v.nametown , v.StHoFl,
v.idpredpr,v.idbank,v.oper,v.FIODir,v.kodmfo,v.StHoFlsklad,v.zipcodesclad
FROM
(
SELECT ISNULL(pr.namePredprShort,'')  AS skladname, ISNULL(pr.StHoFl,'') AS StHoFlsklad, ISNULL(CAST(pr.zipcode AS VARCHAR(10)),'')  AS zipcodesclad,
CASE WHEN pr.idplat = @ID_ENTERPR_SENDER THEN '' --pr.namePredprShort 
ELSE (SELECT namePredprShort FROM maindatabase.dbo.tbpredpr WHERE idpredpr = pr.idplat)  END AS stockNamePredprShort,
ISNULL(CAST(pr.zipcode AS VARCHAR(10)),'') AS zipcode, ISNULL(town.nametown,'') AS nametown, ISNULL(pr.StHoFl,'') AS StHoFl,
oper.namegroper AS oper,ISNULL(pr.FIODir,'') AS FIODir,pr.kodmfo,--dc.idpredpr,
CASE WHEN dc.idpredpr IN (SELECT idplat FROM maindatabase.dbo.tbpredpr WHERE idpredpr = dc.idpredpr) THEN dc.idpredpr
ELSE (SELECT idplat FROM maindatabase.dbo.tbpredpr WHERE idpredpr = pr.idplat) END AS idpredpr,
CASE WHEN pr.idplat = @ID_ENTERPR_SENDER THEN 
(SELECT idbank FROM maindatabase.dbo.tbRschet WHERE idpredpr =  @ID_ENTERPR_SENDER AND osn = 1)
ELSE (SELECT idbank FROM maindatabase.dbo.tbRschet WHERE idpredpr = pr.idplat AND osn = 1)  END AS idbank
FROM maindatabase.dbo.doccaption dc
INNER JOIN maindatabase.dbo.tbpredpr pr ON dc.kodskl = @ID_WAREHOUSE AND dc.iddoc = @ID_DOC AND pr.idpredpr = @ID_WAREHOUSE --AND dc.idpredpr = pr.idpredpr
INNER JOIN maindatabase.dbo.tbtown town ON pr.idtown = town.idtown
INNER JOIN maindatabase.dbo.tbgroper oper ON oper.idgroper = dc.idgroper
) v
) v1
INNER JOIN maindatabase.dbo.tbpredpr pr3 ON pr3.idpredpr = v1.idpredpr
LEFT OUTER JOIN maindatabase.dbo.tbpredpr pr2 ON pr2.idpredpr = v1.idbank
LEFT OUTER JOIN maindatabase.dbo.tbrschet rschet ON rschet.idpredpr = v1.idpredpr
AND rschet.idBank= v1.idbank AND osn = 1

-- Receiver
SELECT v1.enterprName,v1.zipcode,v1.nametown, v1.StHoFl,v1.stockNamePredprShort, ISNULL(rschet.rschet,'') AS  rschet, ISNULL(pr2.kodmfo,'') AS kodmfo,
pr3.dogovor,
v1.idpredpr,v1.idbank,ISNULL(pr2.NamePredprshort,'') AS bankNamePredpr,
pr3.unn AS enterprUnn, pr3.KodOKPO AS enterprKodOKPO, pr3.lic AS enterprLic
FROM 
(
SELECT v.enterprName, v.zipcode,v.nametown, v.StHoFl,v.stockNamePredprShort,
v.idpredpr,v.idbank
FROM
(
SELECT  ISNULL(pr.namePredprShort,'')  AS enterprName,
CASE WHEN pr.idplat = @ID_ENTERPR_RECIPIENT THEN pr.namePredprShort 
ELSE (SELECT namePredprShort FROM maindatabase.dbo.tbpredpr WHERE idpredpr = pr.idplat)  END AS stockNamePredprShort,
ISNULL(CAST(pr.zipcode AS VARCHAR(10)),'') AS zipcode, ISNULL(town.nametown,'') AS nametown,ISNULL(pr.StHoFl,'') AS StHoFl,
CASE WHEN pr.idplat = @ID_ENTERPR_RECIPIENT THEN pr.idpredpr
ELSE (SELECT idpredpr FROM maindatabase.dbo.tbpredpr WHERE idpredpr = pr.idplat)  END AS idpredpr,
CASE WHEN pr.idplat = @ID_ENTERPR_RECIPIENT THEN 
(SELECT idbank FROM maindatabase.dbo.tbRschet WHERE idpredpr =  @ID_ENTERPR_RECIPIENT AND osn = 1)
ELSE (SELECT idbank FROM maindatabase.dbo.tbRschet WHERE idpredpr = pr.idplat AND osn = 1)  END AS idbank
FROM maindatabase.dbo.doccaption dc
INNER JOIN maindatabase.dbo.tbpredpr pr ON dc.idpredpr = pr.idpredpr 
AND dc.idpredpr = @ID_ENTERPR_RECIPIENT AND dc.iddoc = @ID_DOC
INNER JOIN maindatabase.dbo.tbtown town ON pr.idtown = town.idtown
) v
) v1
INNER JOIN maindatabase.dbo.tbpredpr pr3 ON pr3.idpredpr = v1.idpredpr
LEFT OUTER JOIN maindatabase.dbo.tbpredpr pr2 ON pr2.idpredpr = v1.idbank
LEFT OUTER JOIN maindatabase.dbo.tbrschet rschet ON rschet.idpredpr = v1.idpredpr
AND rschet.idBank= v1.idbank AND osn = 1

-- Goods
SELECT RTRIM(goods.namet) + ' ' + ISNULL(sort.namesort,'') AS name_raw_material,
goods.vlajn, goods.jirn, country.namecountry,ediz.shortnameedizm,ds.kolf,ds.ceno,st.vidup,st.minup,
st.art,st.sertif,pr.namePredprShort,ds.nds,ds.naltr,ds.nacopt,ds.skidpokup,ds.nacobpit, ISNULL(st.fasov,0) AS fasov
FROM MainDatabase.dbo.doccaption dc
INNER JOIN MainDatabase.dbo.docstring ds ON dc.iddoc = ds.iddoc AND dc.iddoc = @ID_DOC
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
LEFT OUTER JOIN maindatabase.dbo.tbsort sort ON goods.idsort = sort.idsort
INNER JOIN MainDatabase.dbo.sprtovar st ON st.pnt = ds.pnt
LEFT OUTER JOIN MainDatabase.dbo.tbPredpr pr ON st.idpredpr = pr.idpredpr
LEFT OUTER JOIN MainDatabase.dbo.tbCountry country ON country.idCountry = st.idCountry
LEFT OUTER JOIN MainDatabase.dbo.sprediz ediz ON ediz.edizid = goods.edizid--st.edizid
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ItogForAccount 
@NumOtch INT,
@KodSkl INT,
@START_DATE SMALLDATETIME,
@END_DATE SMALLDATETIME,
@SumTovRemains DECIMAL(18,3) = 0 OUTPUT,
@SumTarRemains DECIMAL(18,3) = 0 OUTPUT,
@SumTovArrivedLeft  DECIMAL(18,3) = 0 OUTPUT,
@SumTarArrivedLeft  DECIMAL(18,3) = 0 OUTPUT
AS
 declare @DateOtch datetime
 set @DateOtch = (select distinct DateOtch from maindatabase.dbo.DocCaption 
                                where  (NumOtch = @NumOtch) and (KodSkl=@KodSkl))
DECLARE  @IdGrOper SMALLINT
SELECT @IdGrOper = REMAINS FROM technolog.dbo.gropersettings
SELECT @SumTovRemains = ISNULL(ABS(v.ARRIVED-v.LEFT_G),0)
FROM (
SELECT 
SUM (CASE WHEN viddoc = 1 THEN  ISNULL(itogotov,0) ELSE 0 END) AS ARRIVED, -- AND (idgroper = 232 OR idgroper = 229 OR idgroper = 233) 
SUM (CASE WHEN viddoc = 2 THEN  ISNULL(itogotov,0) ELSE 0 END) AS LEFT_G --AND (idgroper = 235 OR idgroper = 279 )
FROM maindatabase.dbo.doccaption WHERE (NumOtch < @NumOtch AND NumOtch IS NOT NULL) AND (DateDoc <= @DateOtch)  AND (kodskl = @KodSkl) 
) v 
SELECT @SumTarRemains = ISNULL(ABS(v.ARRIVED-v.LEFT_G),0) 
FROM (
SELECT 
SUM (CASE WHEN viddoc = 1 THEN  ISNULL(itogotar,0) ELSE 0 END) AS ARRIVED,
SUM (CASE WHEN viddoc = 2 THEN  ISNULL(itogotar,0) ELSE 0 END) AS LEFT_G
FROM maindatabase.dbo.doccaption WHERE (NumOtch<@NumOtch AND NumOtch IS NOT NULL) AND (DateDoc <= @DateOtch) AND (kodskl = @KodSkl) 
) v 
SELECT @SumTovArrivedLeft = ISNULL(ABS(v.ARRIVED - v.LEFT_G),0)
FROM (
SELECT 
SUM (CASE WHEN viddoc = 1 THEN  ISNULL(itogotov,0) ELSE 0 END) AS ARRIVED,
SUM (CASE WHEN viddoc = 2 THEN  ISNULL(itogotov,0) ELSE 0 END) AS LEFT_G
FROM maindatabase.dbo.doccaption WHERE (NumOtch = @NumOtch AND NumOtch IS NOT NULL) AND (kodskl = @KodSkl) --AND iddoc = @IdDoc
 --AND (DateDoc >= @DateOtch AND DateDoc <= @END_DATE) 
) v 
SELECT @SumTarArrivedLeft = ISNULL(ABS(v.ARRIVED-v.LEFT_G) ,0)
FROM (
SELECT 
SUM (CASE WHEN viddoc = 1 THEN  ISNULL(itogotar,0) ELSE 0 END) AS ARRIVED,
SUM (CASE WHEN viddoc = 2 THEN  ISNULL(itogotar,0) ELSE 0 END) AS LEFT_G
FROM maindatabase.dbo.doccaption WHERE (NumOtch = @NumOtch AND NumOtch IS NOT NULL) AND (kodskl = @KodSkl)  --AND iddoc = @IdDoc
--AND (DateDoc >= @DateOtch AND DateDoc <= @END_DATE) 
) v

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.ListAllGoodsArrivedByGroup
@GROUPS VARCHAR(1000),
@START_DATE datetime,
@END_DATE datetime
AS
SET NOCOUNT ON
DECLARE @SQL_TEXT VARCHAR(5000) 
SET @SQL_TEXT = 
'SELECT
sgr.namegr,ds.pnt_as_key,RTRIM(goods.namet)  ' + ' + COALESCE(goods.sort,'''') '  + '   ' + ' + COALESCE(cast(goods.vlajn AS VARCHAR(12)),'''')' + '  ' + ' + COALESCE(cast(goods.jirn AS VARCHAR(12)),'''')'  + ' AS namet,
sediz.ediz,ds.kolf,ds.ceno,technolog.dbo.CostRawMaterialArrived(ds.idstr)  AS total 
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
INNER JOIN MainDatabase.dbo.sprtovar st ON ds.pnt = st.pnt
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
INNER JOIN MainDatabase.dbo.sprGrup sgr ON st.kodgr = sgr.kodgr
INNER JOIN MainDatabase.dbo.sprediz sediz ON st.edizid = sediz.edizid
WHERE dc.datedoc <= ''' + CAST(@END_DATE AS VARCHAR(12)) + ''' AND dc.datedoc >= ''' + CAST(@START_DATE AS VARCHAR(12)) 
+ ''' AND dc.viddoc = 1 AND  st.kodgr IN ( ' + @GROUPS +' )  ORDER BY st.kodgr'
--print  @SQL_TEXT
EXEC ( @SQL_TEXT)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.SelGrOperTechnolog
@VidDoc TINYINT
AS
--DECLARE @CODE_ARRIVED_OUT INT
--DECLARE @CODE_LEFT_OUT INT
--DECLARE @CODE_ARRIVED_IN INT
--DECLARE @CODE_LEFT_IN INT
--DECLARE @CODE_REMAINS INT
--EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
--@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT 
--END
IF @VidDoc = 1 
BEGIN
--SELECT IdGrOper, NameGrOper FROM maindatabase.dbo.tbgroper WHERE idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_ARRIVED_IN)
SELECT tOper.IdGrOper, tOper.NameGrOper FROM maindatabase.dbo.tbgroper tOper
INNER JOIN (
SELECT idnamedeist FROM maindatabase.dbo.tbdeist WHERE 
iddeistpar IN (SELECT idnamedeist FROM maindatabase.dbo.tbdeist WHERE namedeist = '10.1 Склад сырья')
AND namedeist = 'Приход'
) v ON v.idnamedeist = tOper.idnamedeist  ORDER BY tOper.NameGrOper
END
IF @VidDoc = 2  
BEGIN
--SELECT IdGrOper, NameGrOper FROM maindatabase.dbo.tbgroper WHERE idgroper IN (@CODE_LEFT_IN,@CODE_LEFT_OUT)
SELECT tOper.IdGrOper, tOper.NameGrOper FROM maindatabase.dbo.tbgroper tOper
INNER JOIN (
SELECT idnamedeist FROM maindatabase.dbo.tbdeist WHERE 
iddeistpar IN (SELECT idnamedeist FROM maindatabase.dbo.tbdeist WHERE namedeist = '10.1 Склад сырья')
AND namedeist = 'Расход'
) v ON v.idnamedeist = tOper.idnamedeist ORDER BY tOper.NameGrOper
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.SelectAccounts 
AS
SELECT idschetsubschet,RTRIM(CAST(kodschet AS VARCHAR(5)) + '.' + CAST(kodsubschet AS VARCHAR(5))) AS account
FROM maindatabase.dbo.tbsprschet WHERE SchetPriz = 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.SelectExistingRawMaterial
@KodSkl int
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT 
 
--END
--IF @Oper <> 229 AND @Oper <> 232 AND @Oper <> 0
-- BEGIN
	SELECT  v.kodgr,v.kodpgr,v.kodvid,v.kodr1,v.kodr2,v.namet,v.sort as namesort,ISNULL(v.vlajn,0) AS vlajn, ISNULL(v.jirn,0) AS jirn,v.ceno,v.sertif,v.pnt,v.prsyrja, 
	v.NalTr, v.SkidPost,v.NacPosr,v.NacObpit,v.SkidPokup, 	
	(v.ARRIVED_OUTSIDE+ARRIVED_INSIDE-v.LEFT_OUTSIDE-LEFT_INSIDE) AS Ostatok FROM(
	SELECT  MAX(st.KodGr) AS kodgr, MAX(st.KodPGr) AS kodpgr, MAX(st.KodVid) AS kodvid, MAX(st.KodR1) AS kodr1, MAX(st.KodR2) AS kodr2, MAX(st.prsyrja) as prsyrja,
	MAX(ds.NalTr) AS NalTr, MAX(ds.SkidPost) AS SkidPost,MAX(ds.NacPosr) AS NacPosr,MAX(ds.NacObpit) AS NacObpit,MAX(ds.SkidPokup) AS SkidPokup, 
	MAX(ds.idstr) AS idstr, MIN(goods.namet) AS namet,MIN(goods.sort) AS sort, ISNULL(MIN(goods.vlajn),0) AS vlajn,ISNULL(MIN(goods.jirn),0) AS jirn, MAX(ds.ceno) AS ceno,MAX(st.sertif) AS sertif,MAX(ds.pnt) AS pnt,
	SUM (CASE dc.viddoc WHEN 1 THEN (CASE dc.idgroper WHEN @CODE_ARRIVED_OUT THEN ds.kolf WHEN @CODE_REMAINS THEN ds.kolf ELSE 0 END) ELSE 0 END) AS ARRIVED_OUTSIDE,
	SUM (CASE dc.viddoc WHEN 2 THEN (CASE dc.idgroper WHEN @CODE_LEFT_OUT THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_OUTSIDE,
	SUM (CASE dc.viddoc WHEN 1 THEN (CASE WHEN dc.idgroper NOT IN (@CODE_ARRIVED_OUT,@CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS ARRIVED_INSIDE,
	SUM (CASE dc.viddoc WHEN 2 THEN (CASE WHEN dc.idgroper NOT IN (@CODE_LEFT_OUT,@CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_INSIDE
	FROM MainDatabase.dbo.docstring ds
	INNER JOIN MainDatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc --AND dc.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) 
	AND dc.kodskl = @KodSkl
	INNER JOIN MainDatabase.dbo.tbgroper grop ON grop.idgroper = dc.idgroper
	INNER JOIN MainDatabase.dbo.SprTovar st ON ds.pnt = st.pnt
	INNER JOIN technolog.dbo.tbgoods goods ON goods.id = ds.pnt_as_key
	GROUP BY ds.pnt_as_key) v
--   END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.SelectRawMaterialReturnToManufacturer
@DateDoc DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT 
--END
SELECT v.kodgr,v.kodpgr,v.kodvid,v.kodr1,v.kodr2,v.pnt,v.idstr,v.namet,v.sort AS namesort,ISNULL(v.vlajn,0) AS vlajn,ISNULL(v.jirn,0) AS jirn, docstring.ceno, v.sertif,v.nds,
v.naltr AS NalTr, v.skidpost AS SkidPost,v.nacposr AS NacPosr,v.nacobpit AS NacObpit,v.skidpokup AS SkidPokup,
(v.ARRIVED_OUTSIDE+ ARRIVED_INSIDE- v.LEFT_OUTSIDE-LEFT_INSIDE) AS Ostatok FROM(
SELECT MAX(st.KodGr) AS kodgr, MAX(st.KodPGr) AS kodpgr, MAX(st.KodVid) AS kodvid, MAX(st.KodR1) AS kodr1, MAX(st.KodR2) AS kodr2,max(ds.pnt) AS pnt,
min(goods.namet) AS namet, min(goods.sort) AS sort, min(goods.vlajn) AS vlajn, min(goods.jirn) AS jirn, max(ds.ceno) as ceno,max(st.sertif) as sertif, MAX(ds.nds) AS nds,
MAX(ds.naltr) AS naltr, MAX(ds.SkidPost) AS skidpost, MAX(ds.NacPosr) AS nacposr, MAX(ds.NacObpit) AS nacobpit, MAX(SkidPokup) AS skidpokup,
sum (case dc.viddoc WHEN 1 THEN (case dc.idgroper when @CODE_ARRIVED_OUT then ds.kolf when @CODE_REMAINS then ds.kolf else 0 end) else 0 end) as ARRIVED_OUTSIDE,
sum (case dc.viddoc WHEN 2 THEN (case dc.idgroper when @CODE_LEFT_OUT then ds.kolf else 0 end) else 0 end) as LEFT_OUTSIDE,
sum (case dc.viddoc WHEN 1 THEN (case WHEN dc.idgroper NOT IN(@CODE_ARRIVED_OUT,@CODE_REMAINS) THEN ds.kolf else 0 end) else 0 end) as ARRIVED_INSIDE,
sum (case dc.viddoc WHEN 2 THEN (case WHEN dc.idgroper NOT IN(@CODE_LEFT_OUT,@CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_INSIDE,
max (case dc.viddoc WHEN 1 THEN (case dc.idgroper when @CODE_ARRIVED_OUT then ds.idstr when @CODE_REMAINS then ds.idstr else 0 end) else 0 end) AS idstr
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc --AND dc.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN)  
AND dc.datedoc <= @DateDoc AND dc.kodskl = @CODE_WAREHOUSE
INNER JOIN MainDatabase.dbo.tbgroper grop ON grop.idgroper = dc.idgroper 
INNER JOIN MainDatabase.dbo.sprTovar st ON ds.pnt = st.pnt and st.PriznSyria IS NOT NULL
INNER JOIN technolog.dbo.tbgoods goods ON goods.id = ds.pnt_as_key
GROUP BY ds.pnt_as_key) v, (SELECT idstr,ceno FROM MainDatabase.dbo.docstring) docstring
WHERE docstring.idstr = v.idstr

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.SelectRawMaterialReturnToWarehouse
@DateDoc DATETIME, @CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
--END
SELECT v.kodgr,v.kodpgr,v.kodvid,v.kodr1,v.kodr2,v.pnt,v.idstr,v.namet,v.sort AS namesort,v.vlajn,v.jirn,docstring.ceno, v.sertif,
NULL AS NalTr, NULL AS SkidPost,NULL AS NacPosr,NULL AS NacObpit,NULL AS SkidPokup, NULL AS NDS
FROM(
SELECT MAX(st.KodGr) AS kodgr, MAX(st.KodPGr) AS kodpgr, MAX(st.KodVid) AS kodvid, MAX(st.KodR1) AS kodr1, MAX(st.KodR2) AS kodr2,max(ds.pnt) AS pnt,
MIN(goods.namet) AS namet, MIN(goods.sort) AS sort, ISNULL(MIN(goods.vlajn),0) AS vlajn, ISNULL(MIN(goods.jirn),0) AS jirn, MAX(ds.ceno) AS ceno,MAX(st.sertif) AS sertif,
SUM (CASE dc.viddoc WHEN 1 THEN (CASE dc.idgroper WHEN @CODE_ARRIVED_OUT THEN ds.kolf WHEN @CODE_REMAINS THEN ds.kolf ELSE 0 END) ELSE 0 END) AS ARRIVED_OUTSIDE,
SUM (CASE dc.viddoc WHEN 2 THEN (CASE dc.idgroper WHEN @CODE_LEFT_OUT THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_OUTSIDE,
SUM (CASE dc.viddoc WHEN 1 THEN (CASE WHEN dc.idgroper NOT IN (@CODE_ARRIVED_OUT,@CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS ARRIVED_INSIDE,
SUM (CASE dc.viddoc WHEN 2 THEN (CASE WHEN dc.idgroper NOT IN (@CODE_LEFT_OUT,@CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_INSIDE,
MAX (CASE dc.viddoc WHEN 1 THEN (CASE dc.idgroper WHEN @CODE_ARRIVED_OUT THEN ds.idstr WHEN @CODE_REMAINS THEN ds.idstr ELSE 0 END) ELSE 0 END) AS idstr
FROM MainDatabase.dbo.docstring ds
INNER JOIN MainDatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc 
--AND dc.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) 
AND dc.datedoc <= @DateDoc AND dc.kodskl = @CODE_WAREHOUSE
INNER JOIN MainDatabase.dbo.tbgroper grop ON grop.idgroper = dc.idgroper 
INNER JOIN MainDatabase.dbo.sprTovar st ON ds.pnt = st.pnt and st.PriznSyria IS NOT NULL
INNER JOIN technolog.dbo.tbgoods goods ON goods.id = ds.pnt_as_key
GROUP BY ds.pnt_as_key) v, (SELECT idstr,ceno FROM MainDatabase.dbo.docstring) docstring
WHERE docstring.idstr = v.idstr
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.SelectRawMaterial_EnterRemains
@Groups VARCHAR(1000) AS
SET NOCOUNT ON
SELECT st.KodGr,st.KodPGr,st.KodVid, max(st.KodR1) as kodr1, max(st.KodR2) as kodr2, 
ISNULL(MAX(st.Vlajn),0) AS vlajn, ISNULL(MAX(st.Jirn),0) AS jirn, MAX(st.NameT) AS namet,
--max(st.KodGr) as kodgr, max(st.KodPGr) as kodpgr, max(st.KodVid) as kodvid, max(st.KodR1) as kodr1, max(st.KodR2) as kodr2,
max(st.PNT) as pnt, max(st.NameTov) as nametov , max(st.EdIzID) as edizid, max(st.IdSort) as idsort,
max(st.PriznSyria) as PriznSyria, max(st.DatePrih) as DatePrih, max(st.SrokGodn) as SrokGodn , MAX(st.prsyrja) AS prsyrja,
max(st.Sertif) as Sertif, max(st.VidUp) as VidUp,
max(st.MinUp) as MinUp, max(st.Fasov) as Fasov, max(st.Art) as art, max(st.IdPredpr) as idpredpr, max(st.IdCountry) as idcountry , 
max(st.PNTTar1) as PNTTar1, max(st.PNTTar2) as PNTTar2 , max(st.Ves) as Ves, max(st.CenO) as CenO, max(st.NDS) as NDS, 
max(se.EdIz) as EdIz, max(srt.NameSort) as NameSort, max(st.IdPriznNac) as IdPriznNac,
NULL AS NalTr, NULL AS SkidPost,NULL AS NacPosr,NULL AS NacObpit,NULL AS SkidPokup
FROM MainDataBase.dbo.SprTovar st 
INNER JOIN  MainDataBase.dbo.SprEdIz se ON se.EdIzID = st.EdIzID
LEFT OUTER JOIN  MainDataBase.dbo.tbSort srt ON srt.IdSort = st.IdSort 
INNER JOIN iter_intlist_to_table (@Groups) temprGroup ON st.kodgr =  temprGroup.number
WHERE st.PriznSyria IS NOT NULL AND st.PriznSyria != '' AND st.namet IS NOT NULL 
GROUP BY st.KodGr,st.KodPGr,st.KodVid,st.kodr1,st.kodr2,st.idsort,st.vlajn,st.jirn
--GROUP BY st.namet,st.sort,st.vlajn,st.jirn


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.tchSelectSyrie
@IdMetodOcenki int,
@KodSkl int,
--@IdEnterprise int,
@Groups varchar(5000)
AS
DECLARE @Cmd varchar(5000)
DECLARE @Skl varchar(500)
DECLARE @Enterprise varchar(500)
-- настройка на конкретный склад
IF @KodSkl  > 0
 BEGIN
  IF @IdMetodOcenki = 1
  BEGIN
   SET @Skl = N'DECLARE @KodSkl int
   SET @KodSkl = ' + CAST(@KodSkl AS varchar(20)) + ' '
   SET @Cmd = @Skl + N' SELECT  st.PNT, st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, st.NameT,  st.NameTov , st.GlKod, 
              dbo.GetOstatok(1, @KodSkl, PNT, GETDATE() ) AS Ostatok,   dbo.GetCena(1, @KodSkl, PNT, GETDATE()) AS CenO,
              srt.NameSort, st.IdSort, se.EdIz, st.EdIzID,  st.PriznSyria,st.PrSyrja, st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp,
              st.Fasov, st.Art, st.Vlajn, st.Jirn, st.IdPredpr, st.IdCountry , st.PNTTar1, st.PNTTar2, st.Ves, st.NDS,  st.IdPriznNac, IdEnterprise = 0,st.cenpriobr
              FROM 
                   MainDatabase.dbo.SprTovar st 
                    LEFT OUTER JOIN MainDatabase.dbo.SprEdIz se ON se.EdIzID = st.EdIzID
                    LEFT OUTER JOIN MainDatabase.dbo.tbSort srt ON srt.IdSort = st.IdSort 
            where PNT in
                 (SELECT PNT from ( SELECT   max(s.PNT) as PNT, st.NameT, st.Vlajn, st.Jirn, srt.NameSort                     
                    FROM MainDatabase.dbo.DocString s
                    JOIN MainDatabase.dbo.DocCaption c ON c.IdDoc = s.IdDoc AND c.KodSkl = @KodSkl
                    JOIN MainDatabase.dbo.SprTovar st ON s.PNT = st.PNT 
                    LEFT OUTER JOIN MainDatabase.dbo.tbSort srt ON srt.IdSort = st.IdSort 
                   GROUP BY st.NameT, st.Vlajn, st.Jirn, srt.NameSort )as q)  ORDER BY NameT'-- ' + @Groups +N'
   END
   ELSE IF @IdMetodOcenki = 2
   BEGIN
   SET @Skl = N'DECLARE @KodSkl int
                        SET @KodSkl = ' + CAST(@KodSkl AS varchar(20)) + ' '
   SET @Cmd = @Skl + 
   N'  SELECT  DISTINCT st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, ds.PNT, st.NameT, st.NameTov,
                  st.GlKod,   dbo.GetOstatok(2, @KodSkl, ds.PNT, GETDATE()) AS Ostatok,
                  dbo.GetCena(2, @KodSkl, st.PNT, GETDATE()) AS CenO, srt.NameSort, st.IdSort, se.EdIz, st.EdIzID,  st.PriznSyria,st.PrSyrja, 
                  st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, st.Vlajn, st.Jirn, st.IdPredpr, st.IdCountry ,
                  st.PNTTar1, st.PNTTar2, st.Ves, st.NDS, st.IdPriznNac,st.cenpriobr
          FROM    MainDatabase.dbo.DocString ds
           INNER JOIN MainDatabase.dbo.DocCaption dc ON ds.IdDoc = dc.IdDoc AND dc.KodSkl = @KodSkl
           INNER JOIN MainDatabase.dbo.SprTovar st ON st.PNT = ds.PNT 
           LEFT OUTER JOIN MainDatabase.dbo.SprEdIz se ON se.EdIzID = st.EdIzID
           LEFT OUTER JOIN MainDatabase.dbo.tbSort srt ON srt.IdSort = st.IdSort ORDER BY st.NameT ' --+ @Groups + N' '
   END
  ELSE IF @IdMetodOcenki = 3
  BEGIN
  SET @Cmd = 
  N'SELECT PNT  AS PNT, st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, 0 as Ostatok, st.CenO, st.NameT, st.NameTov,
                  srt.NameSort, st.IdSort, se.EdIz, st.EdIzID,  st.PriznSyria, st.PrSyrja,
                  st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, st.Vlajn, st.Jirn, st.IdPredpr, st.IdCountry ,
                  st.PNTTar1, st.PNTTar2, st.Ves, st.NDS, st.IdPriznNac,st.cenpriobr
  FROM       MainDatabase.dbo.SprTovar st 
                    LEFT OUTER JOIN MainDatabase.dbo.SprEdIz se ON se.EdIzID = st.EdIzID
                    LEFT OUTER JOIN MainDatabase.dbo.tbSort srt ON srt.IdSort = st.IdSort 
 where PNT in 
  (select PNT from ( SELECT   max(s.PNT) as PNT, st.NameT,st.Vlajn, st.Jirn,  srt.NameSort                     
                    FROM MainDatabase.dbo.DocString s
                    JOIN MainDatabase.dbo.SprTovar st ON s.PNT = st.PNT 
                    LEFT OUTER JOIN MainDatabase.dbo.tbSort srt ON srt.IdSort = st.IdSort 
                   GROUP BY st.NameT, st.Vlajn, st.Jirn, srt.NameSort ) as q)  ORDER BY NameT '-- + @Groups + N' '
  END	
  ELSE IF @IdMetodOcenki = 4
  BEGIN
  SET @Cmd = 
  N'SELECT st.PNT , st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, 0 as Ostatok, st.CenO, st.NameT, st.NameTov,
                  srt.NameSort, st.IdSort, se.EdIz, st.EdIzID,  st.PriznSyria, st.PrSyrja
                  st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, ISNULL(st.Vlajn,0) AS vlajn, ISNULL(st.Jirn,0) AS jirn, st.IdPredpr, st.IdCountry ,
                  st.PNTTar1, st.PNTTar2, st.Ves, st.NDS, st.IdPriznNac,st.cenpriobr
  FROM       MainDatabase.dbo.SprTovar st 
                    LEFT OUTER JOIN MainDatabase.dbo.SprEdIz se ON se.EdIzID = st.EdIzID
                    LEFT OUTER JOIN MainDatabase.dbo.tbSort srt ON srt.IdSort = st.IdSort ' + @Groups 
END
END
-- для Справочника Сырья в Арм Кладовая
ELSE IF @KodSkl <= 0
BEGIN
/*  SET @Enterprise = N' DECLARE @IdEnterprise int
       SET @IdEnterprise = '+ CAST(@IdEnterprise AS varchar(20)) + ' '*/
  SET @Cmd =/* @Enterprise + */
   N'  SELECT st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, st.PNT, st.NameT, st.NameTov , st.EdIzID, st.IdSort, st.PriznSyria, 
	st.PrSyrja,st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, ISNULL(st.Vlajn,0) AS vlajn, ISNULL(st.Jirn,0) AS jirn, st.IdPredpr,st.IdCountry , 
                       st.PNTTar1, st.PNTTar2, st.Ves, st.CenO, st.NDS, se.EdIz, srt.NameSort,  st.IdPriznNac,  syr.IdEnterprise, st.cenpriobr
          FROM MainDataBase.dbo.SprTovar st 
          LEFT OUTER JOIN  MainDataBase.dbo.SprEdIz se ON se.EdIzID = st.EdIzID
          LEFT OUTER JOIN  MainDataBase.dbo.tbSort srt ON srt.IdSort = st.IdSort
          INNER JOIN dbo.tbSyrie  syr ON syr.PNT = st.PNT   '+ @Groups  --  WHERE syr.IdEnterprise = @IdEnterprise   
END
print @Cmd
EXECUTE (@Cmd)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


CREATE PROCEDURE dbo.selectRawMaterialByGroups 
@Groups VARCHAR(1000)
AS
SET NOCOUNT ON
SELECT st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, st.PNT, st.NameT, st.NameTov , st.EdIzID, st.IdSort, st.PriznSyria, 
st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, ISNULL(st.Vlajn,0) AS vlajn, ISNULL(st.Jirn,0) AS jirn, st.IdPredpr,st.IdCountry , 
st.PNTTar1, st.PNTTar2, st.Ves, st.CenO, st.NDS, se.EdIz, srt.NameSort,  st.IdPriznNac,st.nds,st.naltr,st.skidpost,st.nacposr ,st.prsyrja,
0 AS NalTr, 0 AS SkidPost,0 AS NacPosr,0 AS NacObpit,0 AS SkidPokup,ISNULL(st.CenPriobr,0) AS CenPriobr
FROM MainDataBase.dbo.SprTovar st 
INNER JOIN iter_intlist_to_table (@Groups) temprGroup ON st.kodgr =  temprGroup.number
LEFT OUTER JOIN  MainDataBase.dbo.SprEdIz se ON se.EdIzID = st.EdIzID 
and st.PriznSyria IS NOT NULL
LEFT OUTER JOIN  MainDataBase.dbo.tbSort srt ON srt.IdSort = st.IdSort
WHERE st.PriznSyria IS NOT NULL AND st.PriznSyria != '' AND st.namet IS NOT NULL



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.SelectSyrie
@IdMetodOcenki INT,
@KodSkl int,
--@IdEnterprise int,
@Groups VARCHAR(5000),
@Oper INT,
@DateDoc DATETIME,
@ValueOut INT OUTPUT,
@DOC_TYPE TINYINT = 0
AS
SET NOCOUNT ON
SET @ValueOut = 0
IF @Oper = -100
BEGIN
 EXEC tchSelectSyrie @IdMetodOcenki, @KodSkl, @Groups
 RETURN	
END
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
--END
DECLARE @Cmd VARCHAR(5000)
DECLARE @Skl VARCHAR(500)
DECLARE @Enterprise VARCHAR(500)
IF @Oper =  @CODE_ARRIVED_OUT
BEGIN
	SET @ValueOut = 1
END
IF @Oper =  @CODE_LEFT_OUT 
BEGIN
	SET @ValueOut = 2
END
IF @Oper NOT IN (@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_REMAINS) AND @DOC_TYPE = 1 --For arrived_in
BEGIN
	SET @ValueOut = 3
END
IF @Oper NOT IN (@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_REMAINS)  AND @DOC_TYPE = 2 -- @CODE_LEFT_IN 
BEGIN
	SET @ValueOut = 4
END
--IF @Oper <> @CODE_REMAINS AND @Oper <> @CODE_ARRIVED_OUT AND @Oper <> @CODE_ARRIVED_IN AND @Oper <> @CODE_LEFT_OUT AND @Oper > 0 
IF @Oper NOT IN( @CODE_REMAINS,@CODE_ARRIVED_OUT, @CODE_LEFT_OUT) AND @Oper > 0 AND @DOC_TYPE = 2
BEGIN
EXEC dbo.SelectExistingRawMaterial @KodSkl 
END
IF @Oper <= 0 OR @Oper = @CODE_ARRIVED_OUT 
BEGIN
  EXEC dbo.selectRawMaterialByGroups @Groups
END
IF @Oper = @CODE_LEFT_OUT
BEGIN
    EXEC dbo.SelectRawMaterialReturnToManufacturer @DateDoc,@KodSkl
END
--IF @Oper  NOT IN  (@CODE_LEFT_OUT,@CODE_REMAINS)  AND @DOC_TYPE = 1
IF @Oper  NOT IN  (@CODE_ARRIVED_OUT,@CODE_REMAINS)  AND @DOC_TYPE = 1
BEGIN
    EXEC dbo.SelectRawMaterialReturnToWarehouse @DateDoc,@KodSkl
END
IF @Oper  = @CODE_REMAINS
BEGIN
    EXEC dbo.SelectRawMaterial_EnterRemains @Groups
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.SelectWarehouses AS
SELECT Pr.IdPredpr, Pr.namePredprShort FROM maindatabase.dbo.tbPredpr Pr INNER JOIN 
maindatabase.dbo.tbGrPredpr GrPr  ON  Pr.IdGrPredpr = GrPr.IdGrPredpr 
--WHERE GrPr.IdGrPredpr = 25
WHERE (GrPr.NameGrPredpr = 'Склад сырья')

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[calcTotalStr]
@IdDoc INT,
@MODE BIT
AS
IF (@MODE = 0)
BEGIN
UPDATE maindatabase.dbo.DocCaption SET  Itogo = -25 WHERE IdDoc = @IdDoc
RETURN
END

declare @Itogo decimal(18,3)
declare @ItogoTov decimal(18,3)
declare @ItogoTar decimal(18,3)
declare @ItogoTovAvg decimal(18,3)
declare @ItogoTarAvg decimal(18,3)
set @Itogo=(Select Round(Sum(CenO*KolF),2) from maindatabase.dbo.DocString
                      where IdDoc=@IdDoc)
set @ItogoTov=(Select Round(ISNULL(Sum(ds.CenO*ds.KolF),0),2) from maindatabase.dbo.DocString ds
                          INNER JOIN maindatabase.dbo.SprTovar st ON ds.PNT= st.PNT
                          where   ds.IdDoc=@IdDoc and  not( st.KodGr=99 or  (KodGr=93 and KodPGr=0)))
set @ItogoTar=(Select Round(ISNULL(Sum(ds.CenO*ds.KolF),0),2) FROM maindatabase.dbo.DocString ds
                          INNER JOIN maindatabase.dbo.SprTovar st ON ds.PNT= st.PNT
                          where  ds.IdDoc = @IdDoc and (st.KodGr=99 or  (KodGr=93 and KodPGr=0)))
set @ItogoTovAvg=(Select Round(ISNULL(Sum(ds.CenRoz*ds.KolF),0),2) from maindatabase.dbo.DocString ds
                          INNER JOIN maindatabase.dbo.SprTovar st ON ds.PNT= st.PNT
                          WHERE  ds.IdDoc=@IdDoc and  NOT ( st.KodGr=99 or  (KodGr=93 and KodPGr=0)))
set @ItogoTarAvg=(Select Round(ISNULL(Sum(ds.CenRoz*ds.KolF),0),2) from maindatabase.dbo.DocString ds 
                          INNER JOIN maindatabase.dbo.SprTovar st ON ds.PNT= st.PNT
                          where   ds.IdDoc=@IdDoc and ( st.KodGr=99 or  (KodGr=93 and KodPGr=0)))
UPDATE maindatabase.dbo.DocCaption 
SET 
 Itogo = @Itogo,
 ItogoTov  = @ItogoTov,
 ItogoTar = @ItogoTar,
 ItogoTovR = @ItogoTovAvg,
 ItogoTarR = @ItogoTarAvg
WHERE IdDoc = @IdDoc
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[WriteCalculatedTotals] 
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS

DECLARE @ID_DOC INT
WHILE (SELECT count(*) FROM maindatabase.dbo.doccaption WHERE itogo = -25) > 0  
BEGIN
   SELECT TOP 1 @ID_DOC = iddoc FROM maindatabase.dbo.doccaption WHERE itogo = -25
   EXEC calcTotalStr @ID_DOC, 1
END

RETURN


--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT 
--END
-- !!!! START DATE MUST BE FOR THE CURRENT MONTH
DECLARE @temprTable TABLE 
( 
    pnt_as_key INT, 
    iddoc INT,
    avr_price DECIMAL(9,2)
) 
BEGIN TRANSACTION
INSERT INTO @temprTable
SELECT tgr.pnt_as_key,ds.iddoc,min(tgr.avr_price)  FROM technolog.dbo.tbgoodsremains tgr
INNER JOIN maindatabase.dbo.docstring ds ON ds.pnt_as_key = tgr.pnt_as_key
AND tgr.accountdategoods = ( 
SELECT MAX(tgr1.accountdategoods ) FROM technolog.dbo.tbgoodsremains tgr1
WHERE tgr1.pnt_as_key = tgr.pnt_as_key AND tgr1.accountdategoods <= @END_DATE 
)
INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.datedoc <= @END_DATE AND dc.kodskl = @CODE_WAREHOUSE
GROUP BY tgr.pnt_as_key,ds.iddoc
IF @@ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
RETURN
END

-- 1. Calculate total (including packages) for all inside operaions and write the calculated value into doccaption->Itogo field 
UPDATE maindatabase.dbo.doccaption SET itogo = t.sumGoods FROM
(SELECT  SUM(ds.kolf*tp.avr_price) AS sumGoods, tp.iddoc
FROM @temprTable tp 
INNER JOIN maindatabase.dbo.docstring ds ON ds.iddoc = tp.iddoc AND ds.pnt_as_key = tp.pnt_as_key
INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.idgroper NOT IN (@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_REMAINS)
GROUP BY tp.iddoc) t, maindatabase.dbo.doccaption dc1 
WHERE dc1.iddoc = t.iddoc
IF @@ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
RETURN
END

-- 2. Calculate total without packages for all inside operaions and write the calculated value into doccaption->ItogoTov field 
UPDATE maindatabase.dbo.doccaption SET itogotov = t.sumGoods FROM
(SELECT  SUM(ds.kolf*tp.avr_price) AS sumGoods,tp.iddoc
FROM @temprTable tp 
INNER JOIN maindatabase.dbo.docstring ds ON ds.iddoc = tp.iddoc AND ds.pnt_as_key = tp.pnt_as_key
INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.idgroper NOT IN (@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_REMAINS)
INNER JOIN maindatabase.dbo.sprTovar st ON ds.pnt = st.pnt AND st.kodgr NOT IN (93,99)
GROUP BY tp.iddoc) t, maindatabase.dbo.doccaption dc1 
WHERE dc1.iddoc = t.iddoc
IF @@ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
RETURN
END

-- 3. Calculate total of packages for all inside operaions and write the calculated value into doccaption->ItogoTar field 
UPDATE maindatabase.dbo.doccaption SET itogotar = t.sumGoods FROM
(SELECT  SUM(ds.kolf*ds.ceno) AS sumGoods,tp.iddoc
FROM @temprTable tp 
INNER JOIN maindatabase.dbo.docstring ds ON ds.iddoc = tp.iddoc AND ds.pnt_as_key = tp.pnt_as_key
INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.idgroper NOT IN (@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_REMAINS)
INNER JOIN maindatabase.dbo.sprTovar st ON ds.pnt = st.pnt AND st.kodgr IN (93,99)
GROUP BY tp.iddoc) t, maindatabase.dbo.doccaption dc1 
WHERE dc1.iddoc = t.iddoc
IF @@ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
RETURN
END
COMMIT TRANSACTION
-- 4. Calculate total (including packages) for all operaions(excluding inside) of moving of goods 
-- and write the calculated value into doccaption->Itogo field 
--UPDATE maindatabase.dbo.doccaption SET itogo = t.sumGoods FROM
--(SELECT  SUM(ds.kolf*ds.ceno) AS sumGoods,tp.iddoc
--FROM @temprTable tp 
--INNER JOIN maindatabase.dbo.docstring ds ON ds.iddoc = tp.iddoc AND ds.pnt_as_key = tp.pnt_as_key
--INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.idgroper NOT IN (@CODE_ARRIVED_IN,@CODE_LEFT_IN)
--GROUP BY tp.iddoc) t, maindatabase.dbo.doccaption dc1 
--WHERE dc1.iddoc = t.iddoc
-- 5. Calculate total (without packages) for all operaions excluding inside moving of goods 
-- and write the calculated value into doccaption->ItogoTov field 
--UPDATE maindatabase.dbo.doccaption SET itogotov = t.sumGoods FROM
--(SELECT  SUM(ds.kolf*ds.ceno) AS sumGoods,tp.iddoc
--FROM @temprTable tp 
--INNER JOIN maindatabase.dbo.docstring ds ON ds.iddoc = tp.iddoc AND ds.pnt_as_key = tp.pnt_as_key
--INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.idgroper NOT IN (@CODE_ARRIVED_IN,@CODE_LEFT_IN)
--INNER JOIN maindatabase.dbo.sprTovar st ON ds.pnt = st.pnt AND st.kodgr NOT IN (93,99)
--GROUP BY tp.iddoc) t, maindatabase.dbo.doccaption dc1 
--WHERE dc1.iddoc = t.iddoc
-- 6.Calculate total of packages for all outside operaions and write the calculated value into doccaption->ItogoTar field 
--UPDATE maindatabase.dbo.doccaption SET itogotar = t.sumGoods FROM
--(SELECT  SUM(ds.kolf*ds.ceno) AS sumGoods,tp.iddoc
--FROM @temprTable tp 
--INNER JOIN maindatabase.dbo.docstring ds ON ds.iddoc = tp.iddoc AND ds.pnt_as_key = tp.pnt_as_key
--INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.idgroper NOT IN (@CODE_ARRIVED_IN,@CODE_LEFT_IN)
--INNER JOIN maindatabase.dbo.sprTovar st ON ds.pnt = st.pnt AND st.kodgr IN (93,99)
--GROUP BY tp.iddoc) t, maindatabase.dbo.doccaption dc1 
--WHERE dc1.iddoc = t.iddoc
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE calcBalanceSheet 
@PNT_AS_KEY INT,
@START_DATE SMALLDATETIME,
@END_DATE SMALLDATETIME,
@CODE_WAREHOUSE INT
AS
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
--Select the average price  calculated on the end of the mentioned period.
DECLARE @AVR_PRICE DECIMAL(7,2) 
--SELECT @AVR_PRICE = MAX(avr_price) FROM technolog.dbo.tbgoodsremains WHERE pnt_as_key = @PNT_AS_KEY AND code_warehouse = @CODE_WAREHOUSE AND accountdategoods <= @END_DATE
SELECT  TOP 1 @AVR_PRICE = avr_price FROM tbgoodsremains WHERE pnt_as_key = @PNT_AS_KEY AND code_warehouse = @CODE_WAREHOUSE AND accountdategoods <= @END_DATE ORDER BY accountdategoods DESC
SELECT ISNULL(SUM(CASE v.viddoc WHEN 1 THEN v.GOODS_AMOUNT ELSE 0 END),0) AS ARRIVED_GOODS,
ISNULL(SUM(CASE v.viddoc WHEN 2 THEN v.GOODS_AMOUNT ELSE 0 END),0) AS LEFT_GOODS,
ISNULL(SUM(CASE v.viddoc WHEN 1 THEN v.GOODS_SUM ELSE 0 END),0) AS ARRIVED_SUM,
ISNULL(SUM(CASE v.viddoc WHEN 2 THEN v.GOODS_SUM ELSE 0 END),0) AS LEFT_SUM
FROM (
SELECT MIN(dc.viddoc) AS viddoc,
SUM (CASE dc.viddoc WHEN 1 THEN ds.kolf WHEN 2 THEN ds.kolf ELSE 0 END ) AS GOODS_AMOUNT,
ISNULL(
SUM (CASE dc.viddoc WHEN 1 THEN  (CASE WHEN dc.idgroper IN (@CODE_ARRIVED_OUT) THEN technolog.dbo.CostRawMaterialArrived(ds.idstr) 
--WHEN dc.idgroper NOT IN (@CODE_ARRIVED_OUT,@CODE_REMAINS) THEN ds.kolf*@AVR_PRICE END) 
WHEN dc.idgroper NOT IN (@CODE_ARRIVED_OUT) THEN ds.kolf*@AVR_PRICE END) 
WHEN 2 THEN (CASE WHEN dc.idgroper IN(@CODE_LEFT_OUT) THEN dbo.CostRawMaterialLeft (dc.datedoc, ds.iddoc,ds.pnt_as_key,ds.idstr) 
WHEN dc.idgroper NOT IN(@CODE_LEFT_OUT,@CODE_REMAINS) THEN ds.kolf*@AVR_PRICE END) ELSE 0 END),0) AS GOODS_SUM
FROM maindatabase.dbo.doccaption dc
INNER JOIN maindatabase.dbo.docstring ds ON ds.iddoc = dc.iddoc AND ds.pnt_as_key = @PNT_AS_KEY
--INNER JOIN maindatabase.dbo.tbpredpr tbpredpr ON tbpredpr.idpredpr = dc.idpredpr
--INNER JOIN tbgoodsremains tgr ON tgr.pnt_as_key = ds.pnt_as_key AND tgr.code_warehouse = @CODE_WAREHOUSE AND tgr.accountdategoods = dc.datedoc
WHERE dc.datedoc >= @START_DATE AND dc.datedoc <= @END_DATE AND dc.kodskl = @CODE_WAREHOUSE
GROUP BY dc.numdoc,dc.iddoc
--ORDER BY  dc.viddoc
) v
--SELECT * FROM maindatabase.dbo.doccaption dc INNER JOIN maindatabase.dbo.docstring ds ON ds.iddoc = dc.iddoc AND ds.pnt_as_key = @PNT_AS_KEY  
--SELECT * FROM tbgoodsremains WHERE pnt_as_key = @PNT_AS_KEY AND code_warehouse = @CODE_WAREHOUSE  AND accountDateGoods < @START_DATE
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[calcRawMaterialByName] 
@PNT_AS_KEY INT,
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
--@AVR_PRICE DECIMAL(10,3)
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
--Select the average price  calculated on the end of the mentioned period.
DECLARE @AVR_PRICE DECIMAL(7,2) 
SELECT  TOP 1 @AVR_PRICE = avr_price FROM tbgoodsremains WHERE pnt_as_key = @PNT_AS_KEY AND code_warehouse = @CODE_WAREHOUSE AND accountdategoods <= @END_DATE ORDER BY accountdategoods DESC
--print @AVR_PRICE
--RETURN
SELECT dc.numdoc,MIN(dc.datedoc) AS datedoc,MIN(dc.idpredpr) AS idpredpr, -- MIN(tbpredpr.namepredprshort) AS enterprise,
MIN(dc.viddoc) AS viddoc,
SUM (CASE dc.viddoc WHEN 1 THEN ds.kolf WHEN 2 THEN ds.kolf ELSE 0 END ) AS GOODS_AMOUNT,
ISNULL(
SUM (CASE dc.viddoc WHEN 1 THEN  (CASE  WHEN dc.idgroper IN (@CODE_ARRIVED_OUT) THEN technolog.dbo.CostRawMaterialArrived(ds.idstr) 
WHEN dc.idgroper IN (@CODE_REMAINS) THEN ds.kolf*@AVR_PRICE WHEN dc.idgroper NOT IN (@CODE_ARRIVED_OUT,@CODE_REMAINS) THEN ds.kolf*@AVR_PRICE END) 
WHEN 2 THEN (CASE WHEN dc.idgroper IN (@CODE_LEFT_OUT) THEN dbo.CostRawMaterialLeft  (dc.datedoc, ds.iddoc,ds.pnt_as_key,ds.idstr) 
WHEN dc.idgroper NOT IN (@CODE_LEFT_OUT,@CODE_REMAINS) THEN ds.kolf*@AVR_PRICE  END) ELSE 0 END ) ,0) AS GOODS_SUM, @AVR_PRICE AS avr_price -- MIN(tgr.avr_price)
FROM maindatabase.dbo.doccaption dc
INNER JOIN maindatabase.dbo.docstring ds ON ds.iddoc = dc.iddoc AND ds.pnt_as_key = @PNT_AS_KEY
INNER JOIN maindatabase.dbo.tbpredpr tbpredpr ON tbpredpr.idpredpr = dc.idpredpr
--INNER JOIN tbgoodsremains tgr ON ds.pnt_as_key = tgr.pnt_as_key AND tgr.code_warehouse = @CODE_WAREHOUSE AND tgr.accountdategoods = dc.datedoc
WHERE dc.datedoc >= @START_DATE AND dc.datedoc <= @END_DATE AND dc.kodskl = @CODE_WAREHOUSE
GROUP BY dc.numdoc,dc.iddoc
ORDER BY  dc.datedoc,dc.viddoc
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.clcCopyFormuls
@IdRaschPlanCalc int, 
@IdEnterprise int
AS
-- Если нет такого
IF NOT EXISTS ( SELECT IdRaschPlanCalc FROM dbo.tbDataPlanCalc WHERE IdRaschPlanCalc = @IdRaschPlanCalc )
-- Вставляем только формулы, данные пустые
	INSERT INTO dbo.tbDataPlanCalc ( IdRaschPlanCalc, IdFormula )
	SELECT @IdRaschPlanCalc, IdFormula
	FROM dbo.tbFormRaschPlanCalc
             WHERE IdEnterprise = @IdEnterprise
ELSE
-- Вставляем формулы, которые отсутствовали
	INSERT INTO dbo.tbDataPlanCalc ( IdRaschPlanCalc, IdFormula )	
	SELECT @IdRaschPlanCalc, IdFormula
	FROM dbo.tbFormRaschPlanCalc
             WHERE IdFormula NOT IN ( SELECT IdFormula FROM dbo.tbDataPlanCalc WHERE IdRaschPlanCalc = @IdRaschPlanCalc ) AND  IdEnterprise = @IdEnterprise
IF @@ROWCOUNT <> 0 
BEGIN
-- Добавляем данные из последней калькуляции для заданного вида производства
	             DECLARE @LastRaschPlanCalc int
             		SELECT @LastRaschPlanCalc = MAX(dpc.IdRaschPlanCalc) FROM dbo.tbDataPlanCalc dpc
                           INNER JOIN dbo.tbRaschPlanCalc pc ON pc.IdRaschPlanCalc = dpc.IdRaschPlanCalc
		INNER JOIN dbo.tbFactRecCaption rc ON rc.IdFactRec = pc.IdFactRec
		INNER JOIN dbo.tbNormRecCaption nc ON nc.IdNormRec = rc.IdNormRec
		WHERE nc.IdEnterprise = @IdEnterprise AND dpc.IdRaschPlanCalc <> @IdRaschPlanCalc
DECLARE @IdFormula int
DECLARE @Data float
-- Перенос формул
DECLARE crsCopyFormuls CURSOR STATIC
FOR 
	SELECT IdFormula, Data 
	FROM dbo.tbDataPlanCalc
	WHERE IdRaschPlanCalc = @LastRaschPlanCalc
OPEN crsCopyFormuls
FETCH NEXT
FROM crsCopyFormuls
INTO @IdFormula, @Data
WHILE @@FETCH_STATUS = 0
BEGIN
	UPDATE dbo.tbDataPlanCalc
	SET Data = @Data
	WHERE IdRaschPlanCalc = @IdRaschPlanCalc AND IdFormula = @IdFormula
	FETCH NEXT
	FROM crsCopyFormuls
	INTO @IdFormula, @Data
END
CLOSE crsCopyFormuls
DEALLOCATE crsCopyFormuls
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.clcCopyFormulsFact
@IdRaschFactCalc int, 
@IdEnterprise int
AS
-- Если нет такого
IF NOT EXISTS ( SELECT IdRaschFactCalc FROM dbo.tbDataFactCalc WHERE IdRaschFactCalc = @IdRaschFactCalc )
-- Вставляем только формулы, данные пустые
	INSERT INTO dbo.tbDataFactCalc ( IdRaschFactCalc, IdFormula )
	SELECT @IdRaschFactCalc, IdFormula
	FROM dbo.tbFormRaschFaktCalc
             WHERE IdEnterprise = @IdEnterprise
ELSE
-- Вставляем формулы, которые отсутствовали
	INSERT INTO dbo.tbDataFactCalc ( IdRaschFactCalc, IdFormula )	
	SELECT @IdRaschFactCalc, IdFormula
	FROM dbo.tbFormRaschFaktCalc
             WHERE IdFormula NOT IN ( SELECT IdFormula FROM dbo.tbDataFactCalc WHERE IdRaschFactCalc = @IdRaschFactCalc ) AND  IdEnterprise = @IdEnterprise
IF @@ROWCOUNT <> 0 
BEGIN
-- Добавляем данные из последней калькуляции для заданного вида производства
	             DECLARE @LastRaschFactCalc int
             		SELECT @LastRaschFactCalc = MAX(dfc.IdRaschFactCalc) FROM dbo.tbDataFactCalc dfc
                           INNER JOIN dbo.tbRaschFactCalc fc ON fc.IdraschFactCalc = dfc.IdRaschFactCalc   
                           INNER JOIN dbo.tbRaschPlanCalc pc ON pc.IdraschPlanCalc = fc.IdRaschPlanCalc 
		INNER JOIN dbo.tbFactRecCaption rc ON rc.IdFactRec = pc.IdFactRec
		INNER JOIN dbo.tbNormRecCaption nc ON nc.IdNormRec = rc.IdNormRec
		WHERE nc.IdEnterprise = @IdEnterprise AND dfc.IdRaschFactCalc <> @IdRaschFactCalc
DECLARE @IdFormula int
DECLARE @Data float
-- Перенос формул
DECLARE crsCopyFormuls CURSOR STATIC
FOR 
	SELECT IdFormula, Data 
	FROM dbo.tbDataFactCalc
	WHERE IdRaschFactCalc = @LastRaschFactCalc
OPEN crsCopyFormuls
FETCH NEXT
FROM crsCopyFormuls
INTO @IdFormula, @Data
WHILE @@FETCH_STATUS = 0
BEGIN
	UPDATE dbo.tbDataFactCalc
	SET Data = @Data
	WHERE IdRaschFactCalc = @IdRaschFactCalc AND IdFormula = @IdFormula
	FETCH NEXT
	FROM crsCopyFormuls
	INTO @IdFormula, @Data
END
CLOSE crsCopyFormuls
DEALLOCATE crsCopyFormuls
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.clcFormRaschChangePlaces
@IdFormula1 int,
@IdFormula2 int
AS
-- Меняет местами 2 записи в таблице tbFormRasch
DECLARE @IdStatPlan1 int
DECLARE @Formula1 varchar(50)
DECLARE @UchInDoc1 bit
DECLARE @IdOkrugl1 int
DECLARE @IdStatPlan2 int
DECLARE @Formula2 varchar(50)
DECLARE @UchInDoc2 bit
DECLARE @IdOkrugl2 int
SELECT @IdStatPlan1 = IdStatPlan,
       @Formula1 = Formula,
       @UchInDoc1 = UchInDoc,
       @IdOkrugl1 = IdOkrugl
FROM dbo.tbFormRaschPlanCalc
WHERE IdFormula = @IdFormula1
SELECT @IdStatPlan2 = IdStatPlan,
       @Formula2 = Formula,
       @UchInDoc2 = UchInDoc,
       @IdOkrugl2 = IdOkrugl
FROM dbo.tbFormRaschPlanCalc
WHERE IdFormula = @IdFormula2
UPDATE dbo.tbFormRaschPlanCalc
SET IdStatPlan = @IdStatPlan1,
    Formula = @Formula1,
    UchInDoc = @UchInDoc1,
    IdOkrugl = @IdOkrugl1
WHERE IdFormula = @IdFormula2
UPDATE dbo.tbFormRaschPlanCalc
SET IdStatPlan = @IdStatPlan2,
    Formula = @Formula2,
    UchInDoc = @UchInDoc2,
    IdOkrugl = @IdOkrugl2
WHERE IdFormula = @IdFormula1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.clcMoveFields
@IdFormula int
AS
DECLARE @IdFormula1 int
DECLARE @IdFormula2 int
DECLARE crsMoveFields CURSOR STATIC
FOR 
 SELECT IdFormula
 FROM dbo.tbFormRaschPlanCalc
 WHERE IdFormula >= @IdFormula
OPEN crsMoveFields
-- Получение текущих идентификаторов
FETCH NEXT
FROM crsMoveFields
INTO @IdFormula1
WHILE @@FETCH_STATUS = 0
BEGIN
	SELECT @IdFormula2 = IdFormula
	FROM dbo.tbFormRaschPlanCalc
	WHERE IdFormula = (SELECT MAX(IdFormula) FROM dbo.tbFormRaschPlanCalc)
	-- Перенос данных
	EXEC dbo.clcFormRaschChangePlaces @IdFormula1, @IdFormula2
	-- Получение текущих идентификаторов
	FETCH NEXT
	FROM crsMoveFields
	INTO @IdFormula1
END
CLOSE crsMoveFields
DEALLOCATE crsMoveFields

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[clcReestrData]
@IdEnterprise int,
@DatePlanCalc datetime
AS
SELECT DISTINCT _rpc.IdRaschPlanCalc, nrc.PNT, sp.NameStatPlan, dpc.Result
FROM         tbRaschPlanCalc _rpc
INNER JOIN tbDataPlanCalc dpc ON _rpc.IdRaschPlanCalc = dpc.IdRaschPlanCalc
INNER JOIN tbFormRaschPlanCalc frpc ON dpc.IdFormula = frpc.IdFormula 
INNER JOIN tbFactRecCaption frc ON frc.IdFactRec = _rpc.IdFactRec 
INNER JOIN tbNormRecCaption nrc ON nrc.IdNormRec = frc.IdNormRec
INNER JOIN tbStatPlan sp ON sp.IdStatPlan = frpc.IdStatPlan
WHERE     (frpc.Reestr = 1) AND (_rpc.DatePlanCalc = @DatePlanCalc) AND nrc.IdEnterprise = @IdEnterprise AND NOT dpc.Result Is NULL

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.countWeightAvrTurnoverBalanceSheet
@PNT_AS_KEY INT, 
@STARTDATE DATETIME,
@ENDDATE DATETIME,
@START_AVR_PRICE DECIMAL(10,3), --(6,2),
@END_AVR_PRICE DECIMAL(10,3), --(6,2),
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
SELECT v.pnt_as_key, ISNULL(SUM(v.col2),0) AS col2, ISNULL(SUM(v.col3),0) AS col3, ISNULL(SUM(v.col4),0) AS col4, ISNULL(SUM(v.col5),0) AS col5, ISNULL(SUM(v.col6),0) AS col6, ISNULL(SUM(v.col7),0) AS col7 FROM (
SELECT  ds.pnt_as_key,
SUM (CASE WHEN dc.datedoc < @STARTDATE THEN (CASE dc.viddoc when 1 then ds.kolf else 0 end) else 0 end) - 
SUM (CASE WHEN dc.datedoc < @STARTDATE THEN (CASE dc.viddoc when 2 then ds.kolf else 0 end) else 0 end) AS col2,
(SUM (CASE WHEN dc.datedoc < @STARTDATE AND (dc.idgroper = @CODE_ARRIVED_OUT ) THEN (CASE dc.viddoc WHEN 1 THEN technolog.dbo.CostRawMaterialArrived(ds.idstr) ELSE 0 END) ELSE 0 END) + 
SUM (CASE WHEN dc.datedoc < @STARTDATE AND (dc.idgroper = @CODE_REMAINS ) THEN (CASE dc.viddoc WHEN 1 THEN ds.kolf*ds.ceno ELSE 0 END) ELSE 0 END) +
SUM (CASE WHEN dc.datedoc < @STARTDATE AND (dc.idgroper = @CODE_ARRIVED_IN ) THEN (CASE dc.viddoc WHEN 1 THEN ds.kolf*@START_AVR_PRICE ELSE 0 END) ELSE 0 END)) -
--(SUM (CASE WHEN dc.datedoc < @STARTDATE AND (dc.idgroper = @CODE_LEFT_OUT ) THEN (CASE dc.viddoc WHEN 2 THEN ds.kolf*technolog.dbo.GetSpending(dc.datedoc,ds.iddoc,ds.pnt_as_key) ELSE 0 END) ELSE 0 END) + 
(SUM (CASE WHEN dc.datedoc < @STARTDATE AND (dc.idgroper = @CODE_LEFT_OUT ) THEN (CASE dc.viddoc WHEN 2 THEN technolog.dbo.CostRawMaterialLeft(dc.datedoc,ds.iddoc,ds.pnt_as_key,ds.idstr) ELSE 0 END) ELSE 0 END) + 
SUM (CASE WHEN dc.datedoc < @STARTDATE AND (dc.idgroper = @CODE_LEFT_IN ) THEN (CASE dc.viddoc WHEN 2 THEN ds.kolf*@START_AVR_PRICE ELSE 0 END) ELSE 0 END)) AS col3 ,
SUM (CASE WHEN dc.datedoc >= @STARTDATE AND dc.viddoc = 1 AND (dc.idgroper = @CODE_ARRIVED_OUT OR dc.idgroper = @CODE_ARRIVED_IN) THEN ds.kolf ELSE 0 END) AS col4,
SUM (CASE WHEN (dc.datedoc >= @STARTDATE AND dc.viddoc = 1 AND dc.idgroper = @CODE_ARRIVED_OUT) THEN technolog.dbo.CostRawMaterialArrived(ds.idstr) ELSE 0 END) + 
SUM (CASE WHEN (dc.datedoc >= @STARTDATE AND dc.viddoc = 1 AND dc.idgroper NOT IN (@CODE_ARRIVED_OUT,@CODE_REMAINS)) THEN ds.kolf*@END_AVR_PRICE ELSE 0 END) AS col5,
SUM (CASE WHEN dc.datedoc >= @STARTDATE AND dc.viddoc = 2 AND (dc.idgroper = @CODE_LEFT_OUT OR dc.idgroper = @CODE_LEFT_IN) THEN ds.kolf ELSE 0 END) AS col6,
SUM (CASE WHEN (dc.datedoc >= @STARTDATE AND dc.viddoc = 2 AND dc.idgroper = @CODE_LEFT_OUT) THEN technolog.dbo.CostRawMaterialLeft(dc.datedoc,ds.iddoc,ds.pnt_as_key,ds.idstr) ELSE 0 END) +
SUM (CASE WHEN (dc.datedoc >= @STARTDATE AND dc.viddoc = 2 AND dc.idgroper NOT IN (@CODE_LEFT_OUT,@CODE_REMAINS)) THEN ds.kolf*@END_AVR_PRICE ELSE 0 END) AS col7
FROM maindatabase.dbo.docstring ds 
INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc 
--AND dc.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN)
AND dc.datedoc <= @ENDDATE AND ds.pnt_as_key = @PNT_AS_KEY AND dc.numotch IS NOT NULL AND dc.kodskl = @CODE_WAREHOUSE
INNER JOIN  maindatabase.dbo.tbgroper grop ON grop.idgroper = dc.idgroper
INNER JOIN technolog.dbo.tbGoods tGoods ON ds.pnt_as_key = tGoods.id
AND EXISTS (
SELECT tbGoods.namet,tbGoods.sort,tbGoods.vlajn,tbGoods.jirn FROM maindatabase.dbo.docstring ds1
INNER JOIN maindatabase.dbo.doccaption dc1 ON ds1.iddoc = dc1.iddoc and dc1.datedoc >= @STARTDATE 
INNER JOIN technolog.dbo.tbGoods tbGoods ON ds1.pnt_as_key = tbGoods.id)
GROUP BY ds.pnt_as_key,dc.datedoc) v 
GROUP BY v.pnt_as_key
--SELECT v.pnt_as_key, SUM(v.col2) AS col2, SUM(v.col3) AS col3,SUM(v.col4) AS col4,SUM(v.col5) AS col5,SUM(v.col6) AS col6, SUM(v.col7) AS col7 FROM (
--SELECT  ds.pnt_as_key,
--SUM (CASE WHEN dc.datedoc < @STARTDATE THEN (CASE dc.viddoc when 1 then ds.kolf else 0 end) else 0 end) - 
--SUM (CASE WHEN dc.datedoc < @STARTDATE THEN (CASE dc.viddoc when 2 then ds.kolf else 0 end) else 0 end) AS col2,
--(SUM (CASE WHEN dc.datedoc < @STARTDATE AND (dc.idgroper = @CODE_ARRIVED_OUT OR dc.idgroper = @CODE_REMAINS ) THEN (CASE dc.viddoc WHEN 1 THEN ds.kolf*ds.ceno ELSE 0 END) ELSE 0 END) + 
--SUM (CASE WHEN dc.datedoc < @STARTDATE AND (dc.idgroper = @CODE_ARRIVED_IN ) THEN (CASE dc.viddoc WHEN 1 THEN ds.kolf*@START_AVR_PRICE ELSE 0 END) ELSE 0 END)) -
--(SUM (CASE WHEN dc.datedoc < @STARTDATE AND (dc.idgroper = @CODE_LEFT_OUT ) THEN (CASE dc.viddoc WHEN 2 THEN ds.kolf*technolog.dbo.GetSpending(dc.datedoc,ds.iddoc,ds.pnt_as_key) ELSE 0 END) ELSE 0 END) + 
--SUM (CASE WHEN dc.datedoc < @STARTDATE AND (dc.idgroper = @CODE_LEFT_IN ) THEN (CASE dc.viddoc WHEN 2 THEN ds.kolf*@START_AVR_PRICE ELSE 0 END) ELSE 0 END)) AS col3 ,
--SUM (CASE WHEN dc.datedoc >= @STARTDATE AND dc.viddoc = 1 AND (dc.idgroper = @CODE_ARRIVED_OUT OR dc.idgroper = @CODE_ARRIVED_IN) THEN ds.kolf ELSE 0 END) AS col4,
--SUM (CASE WHEN (dc.datedoc >= @STARTDATE AND dc.viddoc = 1 AND dc.idgroper = @CODE_ARRIVED_OUT ) THEN ds.kolf*ds.ceno ELSE 0 END) + 
--SUM (CASE WHEN (dc.datedoc >= @STARTDATE AND dc.viddoc = 1 AND dc.idgroper = @CODE_ARRIVED_IN) THEN ds.kolf*@END_AVR_PRICE ELSE 0 END) AS col5,
--SUM (CASE WHEN dc.datedoc >= @STARTDATE AND dc.viddoc = 2 AND (dc.idgroper = @CODE_LEFT_OUT OR dc.idgroper = @CODE_LEFT_IN) THEN ds.kolf ELSE 0 END) AS col6,
--SUM (CASE WHEN (dc.datedoc >= @STARTDATE AND dc.viddoc = 2 AND dc.idgroper = @CODE_LEFT_OUT) THEN ds.kolf*technolog.dbo.GetSpending(dc.datedoc,ds.iddoc,ds.pnt_as_key) ELSE 0 END) +
--SUM (CASE WHEN (dc.datedoc >= @STARTDATE AND dc.viddoc = 2 AND dc.idgroper = @CODE_LEFT_IN) THEN ds.kolf*@END_AVR_PRICE ELSE 0 END) AS col7
--FROM maindatabase.dbo.docstring ds 
--INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.idgroper in (@CODE_REMAINS,
--@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) AND 
--dc.datedoc <= @ENDDATE AND ds.pnt_as_key = @PNT_AS_KEY AND dc.numotch IS NOT NULL AND dc.kodskl = @CODE_WAREHOUSE
--INNER JOIN  maindatabase.dbo.tbgroper grop ON grop.idgroper = dc.idgroper
--INNER JOIN technolog.dbo.tbGoods tGoods ON ds.pnt_as_key = tGoods.id
--AND EXISTS (
--SELECT tbGoods.namet,tbGoods.sort,tbGoods.vlajn,tbGoods.jirn FROM maindatabase.dbo.docstring ds1
--INNER JOIN maindatabase.dbo.doccaption dc1 ON ds1.iddoc = dc1.iddoc and dc1.datedoc >= @STARTDATE 
--INNER JOIN technolog.dbo.tbGoods tbGoods ON ds1.pnt_as_key = tbGoods.id)
--GROUP BY ds.pnt_as_key,dc.datedoc) v 
--GROUP BY v.pnt_as_key
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.countWeightedAveragePrice 
@DATEDOC DATETIME,
@PNT_AS_KEY INT, 
@STARTDATE DATETIME,
@CALC_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
--END
SELECT v.datedoc,v.pnt_as_key,v.idstr,v.ARRIVED_SUM_OUTSIDE,v.LEFT_SUM_OUTSIDE,v.ARRIVED_OUTSIDE,v.LEFT_OUTSIDE,
v.ARRIVED_INSIDE,v.LEFT_INSIDE,v.remains,v.remains_prise
FROM (
SELECT dc.datedoc,MAX(ds.idstr) AS idstr,MIN( tGoods.namet) AS namet, MIN( tGoods.sort) AS sort, MIN( tGoods.vlajn) AS vlajn, MIN( tGoods.jirn) AS jirn, ds.pnt_as_key,
SUM (CASE dc.viddoc WHEN 1 THEN (case dc.idgroper WHEN @CODE_ARRIVED_OUT THEN ds.kolf*ds.ceno WHEN @CODE_REMAINS THEN ds.kolf*ds.ceno ELSE 0 END) ELSE 0 END) AS ARRIVED_SUM_OUTSIDE,
SUM (CASE dc.viddoc WHEN 2 THEN (case dc.idgroper WHEN @CODE_LEFT_OUT THEN dbo.GetSpending(dc.datedoc,ds.iddoc,ds.pnt_as_key)*ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_SUM_OUTSIDE,
SUM (CASE dc.viddoc WHEN 1 THEN (case dc.idgroper WHEN @CODE_ARRIVED_OUT then ds.kolf else 0 end) else 0 end) AS ARRIVED_OUTSIDE,
SUM (CASE dc.viddoc WHEN 1 THEN (case dc.idgroper WHEN @CODE_REMAINS THEN ds.kolf else 0 end) else 0 end) AS REMAINS,
SUM (CASE dc.viddoc WHEN 1 THEN (case dc.idgroper WHEN @CODE_REMAINS THEN ds.ceno else 0 end) else 0 end) AS REMAINS_PRISE,
SUM (CASE dc.viddoc WHEN 2 THEN (case dc.idgroper WHEN @CODE_LEFT_OUT then ds.kolf else 0 end) else 0 end) AS LEFT_OUTSIDE,
--SUM (CASE dc.viddoc WHEN 1 THEN (case dc.idgroper WHEN @CODE_ARRIVED_IN then ds.kolf else 0 end) else 0 end) AS ARRIVED_INSIDE,
--SUM (CASE dc.viddoc WHEN 2 THEN (case dc.idgroper WHEN @CODE_LEFT_IN THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_INSIDE
SUM (CASE dc.viddoc WHEN 1 THEN (CASE WHEN dc.idgroper NOT IN (@CODE_ARRIVED_OUT,@CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS ARRIVED_INSIDE,
SUM (CASE dc.viddoc WHEN 2 THEN (CASE WHEN dc.idgroper NOT IN (@CODE_LEFT_OUT, @CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_INSIDE
FROM maindatabase.dbo.docstring ds 
INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc --AND dc.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN,@CODE_ARRIVED_IN_1,@CODE_LEFT_IN_1)
AND dc.datedoc <= @DATEDOC 
-- @CALC_DATE has been added to throw rows which had been calculated earlier. Added 26.01.2006. May be I need to use > instead of >=?
AND dc.datedoc >= @CALC_DATE AND ds.pnt_as_key = @PNT_AS_KEY AND dc.kodskl = @CODE_WAREHOUSE
INNER JOIN  maindatabase.dbo.tbgroper grop ON grop.idgroper = dc.idgroper
INNER JOIN technolog.dbo.tbGoods tGoods ON ds.pnt_as_key = tGoods.id
AND EXISTS (
SELECT tbGoods.namet,tbGoods.sort,tbGoods.vlajn,tbGoods.jirn FROM maindatabase.dbo.docstring ds1
INNER JOIN maindatabase.dbo.doccaption dc1 ON ds1.iddoc = dc1.iddoc and dc1.datedoc >= @STARTDATE 
INNER JOIN technolog.dbo.tbGoods tbGoods ON ds1.pnt_as_key = tbGoods.id
)
GROUP BY ds.pnt_as_key,dc.datedoc) v



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE procedure dbo.countWeightedAveragePrice1
@DATEDOC DATETIME,
@PNT_AS_KEY int, 
@STARTDATE datetime,
@CALC_DATE datetime,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
 
--END
SELECT v.datedoc,v.pnt_as_key,v.idstr,v.ARRIVED_SUM_OUTSIDE,v.LEFT_SUM_OUTSIDE,v.ARRIVED_OUTSIDE,v.LEFT_OUTSIDE,v.ARRIVED_INSIDE,v.LEFT_INSIDE,
v.remains,v.remains_prise
FROM (
select  dc.datedoc,max(ds.idstr) as idstr,min( tGoods.namet) as namet, min( tGoods.sort) AS sort, min( tGoods.vlajn) AS vlajn, MIN( tGoods.jirn) AS jirn, ds.pnt_as_key,
sum (case dc.viddoc when 1 then (case dc.idgroper when @CODE_ARRIVED_OUT then ds.kolf*ds.ceno when @CODE_REMAINS then ds.kolf*ds.ceno else 0 end) else 0 end) as ARRIVED_SUM_OUTSIDE,
sum (case dc.viddoc when 2 then (case dc.idgroper when @CODE_LEFT_OUT then dbo.GetSpending(dc.datedoc,ds.iddoc,ds.pnt_as_key)*ds.kolf else 0 end) else 0 end) as LEFT_SUM_OUTSIDE,
sum (case dc.viddoc when 1 then (case dc.idgroper when @CODE_ARRIVED_OUT then ds.kolf else 0 end) else 0 end) as ARRIVED_OUTSIDE,
sum (case dc.viddoc when 1 then (case dc.idgroper when @CODE_REMAINS then ds.kolf else 0 end) else 0 end) as REMAINS,
sum (case dc.viddoc when 1 then (case dc.idgroper when @CODE_REMAINS then ds.ceno else 0 end) else 0 end) as REMAINS_PRISE,
sum (case dc.viddoc when 2 then (case dc.idgroper when @CODE_LEFT_OUT then ds.kolf else 0 end) else 0 end) as LEFT_OUTSIDE,
--sum (case dc.viddoc when 1 then (case dc.idgroper when @CODE_ARRIVED_IN then ds.kolf else 0 end) else 0 end) as ARRIVED_INSIDE,
--sum (case dc.viddoc when 2 then (case dc.idgroper when @CODE_LEFT_IN then ds.kolf else 0 end) else 0 end) as LEFT_INSIDE
SUM (CASE dc.viddoc WHEN 1 THEN (CASE WHEN dc.idgroper NOT IN (@CODE_ARRIVED_OUT, @CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS ARRIVED_INSIDE,
SUM (CASE dc.viddoc WHEN 2 THEN (CASE WHEN dc.idgroper NOT IN (@CODE_LEFT_OUT,@CODE_REMAINS) THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_INSIDE
FROM maindatabase.dbo.docstring ds 
INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND --dc.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN,@CODE_ARRIVED_IN_1,@CODE_LEFT_IN_1) AND 
dc.numotch IS NOT NULL  AND dc.datedoc <= @DATEDOC 
-- @CALC_DATE has been added to throw rows which had been calculated earlier. Added 26.01.2006
AND dc.datedoc >= @CALC_DATE AND ds.pnt_as_key = @PNT_AS_KEY AND dc.kodskl = @CODE_WAREHOUSE
INNER JOIN  maindatabase.dbo.tbgroper grop ON grop.idgroper = dc.idgroper
INNER JOIN technolog.dbo.tbGoods tGoods ON ds.pnt_as_key = tGoods.id
AND EXISTS (
SELECT tbGoods.namet,tbGoods.sort,tbGoods.vlajn,tbGoods.jirn FROM maindatabase.dbo.docstring ds1
INNER JOIN maindatabase.dbo.doccaption dc1 ON ds1.iddoc = dc1.iddoc and dc1.datedoc >= @STARTDATE 
INNER JOIN technolog.dbo.tbGoods tbGoods ON ds1.pnt_as_key = tbGoods.id
)
GROUP BY ds.pnt_as_key,dc.datedoc) v

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.countWeightedAveragePriceTurn
@START_DATE DATETIME,
@END_DATE DATETIME,
@PNT_AS_KEY INT,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT 
SELECT v.datedoc,v.pnt_as_key,v.idstr,ISNULL(v.ARRIVED_SUM_OUTSIDE,0) AS ARRIVED_SUM_OUTSIDE, ISNULL(v.LEFT_SUM_OUTSIDE,0) AS LEFT_SUM_OUTSIDE,
ISNULL(v.ARRIVED_OUTSIDE,0) AS ARRIVED_OUTSIDE,ISNULL(v.LEFT_OUTSIDE,0) AS LEFT_OUTSIDE,ISNULL(v.ARRIVED_INSIDE,0) AS ARRIVED_INSIDE ,ISNULL(v.LEFT_INSIDE,0) AS LEFT_INSIDE,
ISNULL(v.remains,0) AS remains,ISNULL(v.remains_prise,0) AS remains_prise
FROM (
SELECT  dc.datedoc,MAX(ds.idstr) AS idstr,MIN( tGoods.namet) AS namet, MIN( tGoods.sort) AS sort, MIN( tGoods.vlajn) AS vlajn, MIN(tGoods.jirn) AS jirn, ds.pnt_as_key,
SUM(case dc.viddoc when 1 then (case dc.idgroper when @CODE_ARRIVED_OUT then technolog.dbo.CostRawMaterialArrived(ds.idstr) else 0 end) else 0 end) as ARRIVED_SUM_OUTSIDE,
SUM(case dc.viddoc when 2 then (case dc.idgroper when @CODE_LEFT_OUT then technolog.dbo.CostRawMaterialLeft(dc.datedoc,ds.iddoc,ds.pnt_as_key,ds.idstr) else 0 end) else 0 end) as LEFT_SUM_OUTSIDE,
SUM(case dc.viddoc when 1 then (case dc.idgroper when @CODE_ARRIVED_OUT then ds.kolf else 0 end) else 0 end) as ARRIVED_OUTSIDE,
SUM(case dc.viddoc when 1 then (case dc.idgroper when @CODE_REMAINS then ds.kolf else 0 end) else 0 end) as REMAINS,
SUM(case dc.viddoc when 1 then (case dc.idgroper when @CODE_REMAINS then ds.ceno else 0 end) else 0 end) as REMAINS_PRISE,
SUM (case dc.viddoc when 2 then (case dc.idgroper when @CODE_LEFT_OUT then ds.kolf else 0 end) else 0 end) as LEFT_OUTSIDE,
SUM (case dc.viddoc when 1 then (case WHEN dc.idgroper NOT IN (@CODE_ARRIVED_OUT,@CODE_REMAINS) THEN ds.kolf ELSE 0 END) else 0 end) as ARRIVED_INSIDE,
SUM (case dc.viddoc when 2 then (case WHEN dc.idgroper NOT IN (@CODE_LEFT_OUT,@CODE_REMAINS) THEN ds.kolf ELSE 0 END) else 0 end) as LEFT_INSIDE
FROM maindatabase.dbo.docstring ds 
INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc --AND dc.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) 
INNER JOIN maindatabase.dbo.tbgroper grop ON grop.idgroper = dc.idgroper
INNER JOIN technolog.dbo.tbGoods tGoods ON ds.pnt_as_key = tGoods.id
WHERE dc.datedoc >= @START_DATE AND dc.datedoc <= @END_DATE AND ds.pnt_as_key = @PNT_AS_KEY AND 
dc.kodskl = @CODE_WAREHOUSE 
GROUP BY ds.pnt_as_key,dc.datedoc) v
--SELECT v.datedoc,v.pnt_as_key,v.idstr,v.ARRIVED_SUM_OUTSIDE,v.LEFT_SUM_OUTSIDE,v.ARRIVED_OUTSIDE,v.LEFT_OUTSIDE,v.ARRIVED_INSIDE,v.LEFT_INSIDE,
--v.remains,v.remains_prise
--FROM (
--SELECT  dc.datedoc,MAX(ds.idstr) AS idstr,MIN( tGoods.namet) AS namet, MIN( tGoods.sort) AS sort, MIN( tGoods.vlajn) AS vlajn, MIN( tGoods.jirn) AS jirn, ds.pnt_as_key,
--sum (case dc.viddoc when 1 then (case dc.idgroper when @CODE_ARRIVED_OUT then ds.kolf*ds.ceno else 0 end) else 0 end) as ARRIVED_SUM_OUTSIDE,
--sum (case dc.viddoc when 2 then (case dc.idgroper when @CODE_LEFT_OUT then dbo.GetSpending(dc.datedoc,ds.iddoc,ds.pnt_as_key)*ds.kolf else 0 end) else 0 end) as LEFT_SUM_OUTSIDE,
--sum (case dc.viddoc when 1 then (case dc.idgroper when @CODE_ARRIVED_OUT then ds.kolf else 0 end) else 0 end) as ARRIVED_OUTSIDE,
--sum (case dc.viddoc when 1 then (case dc.idgroper when @CODE_REMAINS then ds.kolf else 0 end) else 0 end) as REMAINS,
--sum (case dc.viddoc when 1 then (case dc.idgroper when @CODE_REMAINS then ds.ceno else 0 end) else 0 end) as REMAINS_PRISE,
--sum (case dc.viddoc when 2 then (case dc.idgroper when @CODE_LEFT_OUT then ds.kolf else 0 end) else 0 end) as LEFT_OUTSIDE,
--sum (case dc.viddoc when 1 then (case dc.idgroper when @CODE_ARRIVED_IN then ds.kolf else 0 end) else 0 end) as ARRIVED_INSIDE,
--sum (case dc.viddoc when 2 then (case dc.idgroper when @CODE_LEFT_IN then ds.kolf else 0 end) else 0 end) as LEFT_INSIDE
--FROM maindatabase.dbo.docstring ds 
--INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,
--@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) 
--INNER JOIN maindatabase.dbo.tbgroper grop ON grop.idgroper = dc.idgroper
--INNER JOIN technolog.dbo.tbGoods tGoods ON ds.pnt_as_key = tGoods.id
--WHERE dc.datedoc >= @START_DATE AND dc.datedoc <= @END_DATE AND ds.pnt_as_key = @PNT_AS_KEY AND 
--dc.kodskl = @CODE_WAREHOUSE 
--GROUP BY ds.pnt_as_key,dc.datedoc) v
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


CREATE PROCEDURE dbo.delAccount
@NumOtch int,
@KodSkl int
 AS
 update maindatabase.dbo.DocCaption
      set NumOtch=null,
            DateOtch=null,
            TabN=null
 where (NumOtch=@NumOtch) and (KodSkl= @KodSkl)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.delDocCaption
@IdDoc int
AS
 DECLARE @DEL_CAPTION_ERROR INT
 DECLARE @DEL_STRING_ERROR INT
 	
 BEGIN TRAN	
 --DELETE FROM technolog.dbo.tbgoodsremains WHERE PNT_AS_KEY IN (SELECT   	
 DELETE FROM maindatabase.dbo.DocString WHERE IdDoc = @IdDoc
 SET @DEL_CAPTION_ERROR = @@ERROR
 DELETE FROM maindatabase.dbo.DocCaption WHERE IdDoc = @IdDoc
 SET @DEL_STRING_ERROR = @@ERROR
 IF  @DEL_CAPTION_ERROR <> 0 OR @DEL_STRING_ERROR <> 0
 BEGIN
 ROLLBACK TRAN	
 RAISERROR ('Fatal error of severity %d raised. ',16,1) 
 END
 ELSE
 BEGIN
   COMMIT TRANSACTION
 END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.delDocString
@IdStr INT
AS
DELETE FROM Maindatabase.dbo.DocString 
WHERE IdStr = @IdStr

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


CREATE PROCEDURE dbo.delDocumentFromAccount
@IdDoc int
 AS
 update maindatabase.dbo.DocCaption
      set NumOtch=null,
            DateOtch=null,
            TabN=null
 where IdDoc  = @IdDoc



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[delFactRecCaption]
@Original_IdFactRec int 
AS
DELETE FROM dbo.tbFactRecCaption
 WHERE     (IdFactRec = @Original_IdFactRec)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[delFactRecString] 
@Original_IdFactStr int
AS
DELETE FROM dbo.tbFactRecString
 WHERE     (IdFactStr = @Original_IdFactStr)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.delMol
@TABN INT
AS
DELETE FROM maindatabase.dbo.spr_works  WHERE tabn = @TABN
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.delPriznSyria
(
	@Original_IDPriznSyria smallint
)
AS
	SET NOCOUNT OFF;
DELETE FROM MainDataBase.dbo.SprPriznSyria WHERE (IDPriznSyria = @Original_IDPriznSyria)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE [dbo].[delProduction] 
@PNT INT,
@IdEnterprise INT
AS
DELETE FROM tbProd WHERE (PNT = @PNT) AND (IdEnterprise = @IdEnterprise);
IF (SELECT COUNT(*) FROM maindatabase.dbo.docstring WHERE pnt = @PNT) <=0 
BEGIN
	DELETE FROM maindatabase.dbo.sprtovar WHERE pnt = @PNT  
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[delSyrie]
 @PNT int,
 @IdEnterprise int
 AS
IF EXISTS (SELECT * FROM technolog.dbo.tbsyrie WHERE PNT = @PNT) -- AND IdEnterprise = @IdEnterprise)
BEGIN
  BEGIN TRANSACTION
  DELETE FROM dbo.tbSyrie WHERE (PNT = @PNT) --and (IdEnterprise = @IdEnterprise)
  IF @@ERROR <> 0
  BEGIN
    ROLLBACK TRANSACTION
    RETURN
  END
  DELETE FROM Maindatabase.dbo.SprTovar  WHERE (PNT = @PNT)
  IF @@ERROR <> 0
  BEGIN
     ROLLBACK TRANSACTION
     RETURN
  END
COMMIT TRANSACTION
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.getEnterprises_RawMaterialByName
@CODES_PNT VARCHAR(3000)
--@START_DATE DATETIME,
--@END_DATE DATETIME,
--@CODE_WAREHOUSE INT
AS
SELECT DISTINCT tbE.idpredpr, tbE.namePredprShort FROM maindatabase.dbo.tbpredpr tbE
INNER JOIN iter_intlist_to_table (@CODES_PNT) listPnt ON listPnt.number = tbE.idpredpr
--SELECT DISTINCT tbE.idpredpr, tbE.namePredprShort FROM maindatabase.dbo.tbpredpr tbE
--INNER JOIN maindatabase.dbo.doccaption dc ON dc.idpredpr = tbE.idpredpr
--INNER JOIN maindatabase.dbo.docstring ds ON dc.iddoc = ds.iddoc 
--INNER JOIN iter_intlist_to_table (@CODES_PNT) listPnt ON ds.pnt_as_key =  listPnt.number

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.getGoodsForTurnroundDoc 
--@STARTDATE DATETIME,
@ENDDATE DATETIME,
@CODE_WAREHOUSE INT
--@PREVIOUS_MONTH DATETIME
AS
SET NOCOUNT ON
--START
DECLARE @STARTDATE DATETIME
SET @STARTDATE = '01/01/2005'
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
--END
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
SELECT MAX(ds1.code_gr) AS code_gr, MAX(ds1.code_subgr) AS code_subgr, MAX(ds1.code_assort) AS code_assortment,
ds1.pnt_as_key, MAX(ds1.pnt) AS pnt, ISNULL(MAX(ds1.namet),0) AS namet, ISNULL(MAX(ds1.sort),'') AS sort, MAX(ds1.vlajn) AS vlajn, MAX(ds1.jirn) AS jirn,
ISNULL(MAX(ds1.remains),0) AS remains, ISNULL(MAX(ds1.price),0) AS price, MAX(ds1.accountDateGoods) AS accountDateGoods, MAX(ds1.datedoc) AS LAST_DATE,
ISNULL(MAX(arrived_amount),0) AS arrived_amount, ISNULL(MAX(arrived_sum),0) AS arrived_sum, ISNULL(MAX(left_amount),0) AS left_amount,
ISNULL(MAX(left_sum),0) AS left_sum,MIN(ds1.idgroper) AS idgroper
FROM ( 
--
SELECT ds.pnt_as_key, ds.idstr,ds.pnt,goods.namet,goods.code_gr,goods.code_subgr,goods.code_assort,
CASE goods.sort WHEN 'б/с' THEN '' ELSE goods.sort END AS sort, 
CASE WHEN goods.vlajn > 0  THEN CAST(goods.vlajn AS VARCHAR(10)) ELSE '' END AS vlajn,
CASE WHEN goods.jirn > 0  THEN CAST(goods.jirn AS VARCHAR(10)) ELSE '' END AS jirn,
COALESCE(NULLIF(gr.remains,NULL),0) remains, 
COALESCE(NULLIF(gr.avr_price,NULL),0) price, gr.accountDateGoods,dc.datedoc,gr.arrived_amount,gr.arrived_sum,gr.left_amount,gr.left_sum,
CASE dc.idgroper WHEN @CODE_REMAINS THEN 1 ELSE 0 END AS idgroper 
FROM maindatabase.dbo.docstring ds
INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.kodskl = @CODE_WAREHOUSE
AND ds.pnt_as_key IS NOT NULL AND ds.pnt_as_key > 0 --AND dc.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) 
AND dc.datedoc <= @ENDDATE
--This part allows exclude goods which haven't been included in reports
AND NOT EXISTS (
SELECT ds_e.pnt_as_key FROM maindatabase.dbo.doccaption dc1 
INNER JOIN maindatabase.dbo.docstring ds_e ON dc1.iddoc = ds_e.iddoc 
--AND dc1.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) AND dc1.datedoc <= @ENDDATE
AND dc1.numotch IS NULL AND ds.pnt_as_key = ds_e.pnt_as_key) 
INNER JOIN technolog.dbo.tbgoods goods ON goods.id = ds.pnt_as_key
LEFT OUTER JOIN technolog.dbo.tbgoodsremains gr ON 
gr.pnt_as_key = goods.id AND gr.accountDateGoods = ( SELECT MAX(gr1.accountDateGoods)
FROM technolog.dbo.tbgoodsremains gr1
WHERE gr1.pnt_as_key = gr.pnt_as_key AND gr1.accountDateGoods <= @ENDDATE)
) ds1 GROUP BY ds1.pnt_as_key
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



CREATE PROCEDURE dbo.getGoodsForTurnroundDocDuplicate
@STARTDATE DATETIME,
@ENDDATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
--END
--DECLARE @BEFORE_START_DATE DATETIME
--SET @BEFORE_START_DATE = DATEADD(day, -1,@STARTDATE)
SELECT MAX(ds1.code_gr) AS code_gr,max(ds1.code_subgr) AS code_subgr,max(ds1.code_assort) AS code_assortment,
ds1.pnt_as_key,MAX(ds1.pnt) AS pnt,MAX(ds1.namet) AS namet, MAX(ds1.sort) AS sort, MAX(ds1.vlajn) AS vlajn, MAX(ds1.jirn) AS jirn,
MAX(ds1.remains) AS remains, MAX(ds1.price) AS price, MAX(ds1.accountDateGoods) AS accountDateGoods
FROM (
SELECT ds.pnt_as_key,ds.idstr,ds.pnt,goods.namet,goods.code_gr,goods.code_subgr,goods.code_assort,
goods.sort,goods.vlajn,goods.jirn,COALESCE(NULLIF(gr.remains,NULL),0) remains, 
COALESCE(NULLIF(gr.avr_price,NULL),0) price, gr.accountDateGoods FROM maindatabase.dbo.docstring ds
INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.kodskl = @CODE_WAREHOUSE
AND ds.pnt_as_key IS NOT NULL AND ds.pnt_as_key > 0 AND dc.idgroper in (@CODE_REMAINS,@CODE_ARRIVED_OUT,
@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) 
--AND dc.datedoc <= @STARTDATE AND dc.numotch IS NOT NULL
AND dc.datedoc <= @ENDDATE
AND NOT EXISTS (
SELECT ds_e.pnt_as_key FROM maindatabase.dbo.doccaption dc1 
INNER JOIN maindatabase.dbo.docstring ds_e ON dc1.iddoc = ds_e.iddoc 
AND dc1.idgroper in (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) 
AND dc1.datedoc <= @ENDDATE
--dc1.datedoc <= @STARTDATE AND dc1.idgroper in (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) 
AND dc1.numotch IS NULL AND ds.pnt_as_key = ds_e.pnt_as_key) AND EXISTS
(
SELECT ds2.pnt_as_key FROM maindatabase.dbo.docstring ds2
INNER JOIN maindatabase.dbo.doccaption dc2 ON dc2.iddoc = ds2.iddoc AND dc2.kodskl = @CODE_WAREHOUSE
AND ds2.pnt_as_key IS NOT NULL AND ds2.pnt_as_key > 0
AND dc2.idgroper IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) 
AND dc2.datedoc >= @STARTDATE AND dc2.datedoc <= @ENDDATE AND ds.pnt_as_key = ds2.pnt_as_key
)
INNER JOIN technolog.dbo.tbgoods goods ON goods.id = ds.pnt_as_key
LEFT OUTER JOIN technolog.dbo.tbgoodsremains gr ON 
gr.pnt_as_key = goods.id AND gr.accountDateGoods = ( SELECT max(gr1.accountDateGoods)
FROM technolog.dbo.tbgoodsremains gr1 WHERE gr1.pnt_as_key = gr.pnt_as_key 
AND gr.accountDateGoods <= @STARTDATE ) 
) ds1 GROUP BY ds1.pnt_as_key
--SELECT MAX(ds1.code_gr) AS code_gr,max(ds1.code_subgr) AS code_subgr,max(ds1.code_assort) AS code_assortment,
--ds1.pnt_as_key,MAX(ds1.pnt) AS pnt,MAX(ds1.namet) AS namet, MAX(ds1.sort) AS sort, MAX(ds1.vlajn) AS vlajn, MAX(ds1.jirn) AS jirn,
--MAX(ds1.remains) AS remains, MAX(ds1.price) AS price, MAX(ds1.accountDateGoods) AS accountDateGoods
--FROM ( SELECT ds.pnt_as_key,ds.idstr,ds.pnt,goods.namet,goods.code_gr,goods.code_subgr,goods.code_assort,
--goods.sort,goods.vlajn,goods.jirn,COALESCE(NULLIF(gr.remains,NULL),0) remains, 
--COALESCE(NULLIF(gr.avr_price,NULL),0) price, gr.accountDateGoods FROM maindatabase.dbo.docstring ds
--INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.kodskl = @CODE_WAREHOUSE
--AND ds.pnt_as_key IS NOT NULL AND ds.pnt_as_key > 0 AND dc.idgroper in (229,232,235,233,234) 
--AND dc.datedoc <= @ENDDATE AND dc.numotch IS NOT NULL
--AND EXISTS ( SELECT dc1.iddoc FROM maindatabase.dbo.doccaption dc1
--WHERE dc1.datedoc >= @STARTDATE AND dc1.datedoc <= @ENDDATE AND dc1.iddoc = dc.iddoc )
--INNER JOIN technolog.dbo.tbgoods goods ON goods.id = ds.pnt_as_key
--LEFT OUTER JOIN technolog.dbo.tbgoodsremains gr ON 
--gr.pnt_as_key = goods.id AND gr.accountDateGoods = ( SELECT max(gr1.accountDateGoods)
--FROM technolog.dbo.tbgoodsremains gr1 WHERE gr1.pnt_as_key = gr.pnt_as_key AND gr.accountDateGoods <= @STARTDATE ) 
--) ds1 GROUP BY ds1.pnt_as_key



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.getGoodsWeightAvrPrise 
@STARTDATE DATETIME,
@ENDDATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
--END
SELECT ds1.pnt_as_key,MAX(ds1.pnt) AS pnt,MAX(ds1.namet) AS namet,-- MAX(ds1.idstr),
MAX(ds1.sort) AS sort, MAX(ds1.vlajn) AS vlajn, MAX(ds1.jirn) AS jirn,
MAX(ds1.remains) AS remains, MAX(ds1.price) AS price, 
MAX(ds1.accountDateGoods) AS accountDateGoods
FROM ( SELECT ds.pnt_as_key,ds.idstr,ds.pnt,goods.namet,goods.sort,goods.vlajn,goods.jirn
,COALESCE(NULLIF(gr.remains,NULL),0) remains, 
COALESCE(NULLIF(gr.avr_price,NULL),0) price, gr.accountDateGoods
FROM maindatabase.dbo.docstring ds
INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.kodskl = @CODE_WAREHOUSE
AND ds.pnt_as_key IS NOT NULL AND ds.pnt_as_key > 0
--AND dc.idgroper in (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) 
AND dc.datedoc >= @STARTDATE AND dc.datedoc <= @ENDDATE
INNER JOIN technolog.dbo.tbgoods goods ON goods.id = ds.pnt_as_key
LEFT OUTER JOIN technolog.dbo.tbgoodsremains gr ON --ds.pnt_as_key = gr.pnt_as_key AND
gr.pnt_as_key = goods.id AND gr.accountDateGoods = ( SELECT MAX(gr1.accountDateGoods)
FROM technolog.dbo.tbgoodsremains gr1 WHERE gr1.pnt_as_key = gr.pnt_as_key AND gr1.accountDateGoods < @STARTDATE  ) 
) ds1 GROUP BY ds1.pnt_as_key --,ds1.pnt,ds1.namet,ds1.sort,ds1.vlajn,ds1.jirn
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[getRawMaterialByName] 
@START_DATE DATETIME,
@END_DATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
SELECT DISTINCT goods.code_gr, goods.code_subgr,goods.code_assort,goods.id AS pnt_as_key,
RTRIM(goods.namet) + ' '  + CASE goods.sort WHEN 'б/с' THEN '' ELSE goods.sort END + ' ' +
+ CASE goods.vlajn WHEN 0 THEN '' WHEN NULL THEN '' ELSE CAST(goods.vlajn AS VARCHAR(6)) END + ' '
+ CASE goods.jirn WHEN 0 THEN '' WHEN NULL THEN '' ELSE CAST(goods.jirn AS VARCHAR(6)) END AS namet
--,tgr.avr_price 
FROM maindatabase.dbo.docstring ds
INNER JOIN maindatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.numotch IS NOT NULL AND dc.datedoc >= @START_DATE AND dc.datedoc <= @END_DATE AND dc.kodskl = @CODE_WAREHOUSE
INNER JOIN technolog.dbo.tbgoods goods ON ds.pnt_as_key = goods.id
AND goods.id NOT IN (
SELECT DISTINCT goods1.id FROM technolog.dbo.tbgoods goods1 
INNER JOIN maindatabase.dbo.docstring ds1 ON ds1.pnt_as_key = goods1.id
INNER JOIN maindatabase.dbo.doccaption dc1 ON dc1.iddoc = ds1.iddoc 
AND dc1.numotch IS NULL) 
--INNER JOIN technolog.dbo.tbgoodsremains tgr ON goods.id = tgr.pnt_as_key AND
--tgr.accountdategoods = ( 
--SELECT MAX(tgr1.accountdategoods) FROM technolog.dbo.tbgoodsremains tgr1
--WHERE tgr.pnt_as_key = tgr1.pnt_as_key GROUP BY tgr1.pnt_as_key
-- ) 
LEFT OUTER JOIN maindatabase.dbo.tbsort sort ON goods.idsort = sort.idsort
 --AND ds.pnt_as_key IS NOT NULL
-- Do I really need it ?
ORDER BY goods.code_gr, goods.code_subgr,goods.code_assort
--,dc.datedoc,dc.viddoc
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[getRegistry]
 @IdReestrCenRoz int, 
 @DateBegin DateTime,
 @DateEnd DateTime
AS
SELECT _rpc.IdRaschPlanCalc, nrc.PNT, st.NameT, ss.NameSort, st.Fasov, _rpc.DatePlanCalc, dpc.IdFormula, sp.NameStatPlan, dpc.Result 
FROM tbRaschPlanCalc _rpc INNER JOIN 
     tbDataPlanCalc dpc ON _rpc.IdRaschPlanCalc = dpc.IdRaschPlanCalc INNER JOIN 
     tbFormRaschPlanCalc frpc ON dpc.IdFormula = frpc.IdFormula INNER JOIN 
     tbFactRecCaption frc ON frc.IdFactRec = _rpc.IdFactRec INNER JOIN 
     tbNormRecCaption nrc ON nrc.IdNormRec = frc.IdNormRec INNER JOIN 
     tbStatPlan sp ON sp.IdStatPlan = frpc.IdStatPlan LEFT OUTER JOIN
     MainDataBase.dbo.SprTovar st ON nrc.PNT = st.PNT LEFT OUTER JOIN
     MainDataBase.dbo.tbSort ss ON st.IdSort = ss.IdSort 
WHERE (frpc.Reestr = 1) AND (_rpc.IdRaschPlanCalc IN 
     (
       SELECT tbRaschPlanCalc.IdRaschPlanCalc 
       FROM tbRaschPlanCalc INNER JOIN 
            tbFactRecCaption ON tbRaschPlanCalc.IdFactRec = tbFactRecCaption.IdFactRec INNER JOIN 
            tbNormRecCaption ON tbFactRecCaption.IdNormRec = tbNormRecCaption.IdNormRec 
       WHERE (tbRaschPlanCalc.DatePlanCalc BETWEEN @DateBegin AND @DateEnd) AND (tbNormRecCaption.PNT IN 
             (
               SELECT tbReestrCenRozString.PNT
               FROM tbReestrCenRozString LEFT OUTER JOIN 
                    MainDataBase.dbo.SprTovar st ON tbReestrCenRozString.PNT = st.PNT LEFT OUTER JOIN 
                    MainDataBase.dbo.tbSort ss ON st.IdSort = ss.IdSort 
               WHERE (tbReestrCenRozString.IdReestrCenRoz = @IdReestrCenRoz
             ))
      )))
ORDER BY nrc.PNT, _rpc.DatePlanCalc

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.getRemainsOfGoods 
@END_DATE DATETIME,
@MODE INT,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
IF @MODE = 0
BEGIN
 SELECT DISTINCT goods.code_gr AS code_gr,goods.code_subgr AS code_subgr,goods.code_assort AS code_assortment,
 ds.pnt_as_key AS pnt_as_key,RTRIM(goods.namet) + ' ' + COALESCE(NULLIF(goods.sort,'б/с'),'') 
 + ' ' + COALESCE(NULLIF(CAST(goods.vlajn AS VARCHAR(12)),'0.00'),'') 
 + ' ' + COALESCE(NULLIF(CAST(goods.jirn AS VARCHAR(12)),'0.00'),'') AS name,sed.shortnameedizm AS unit,
 COALESCE(NULLIF(gr.remains,NULL),0) remains, 
 COALESCE(NULLIF(gr.avr_price,NULL),0) price, gr.accountDateGoods,
 CASE goods.code_gr WHEN 93 THEN 1 WHEN 99 THEN 1 ELSE 0 END AS PACKAGE_BOOL 
 FROM Maindatabase.dbo.docstring ds 
 INNER JOIN Maindatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc  AND dc.datedoc <= @END_DATE 
-- AND dc.kodskl = @CODE_WAREHOUSE
 INNER JOIN technolog.dbo.tbgoods goods ON goods.id = ds.pnt_as_key
 LEFT OUTER JOIN technolog.dbo.tbgoodsremains gr ON ds.pnt_as_key = gr.pnt_as_key AND
 gr.pnt_as_key = goods.id AND gr.accountDateGoods = ( SELECT MAX(gr1.accountDateGoods)
 FROM technolog.dbo.tbgoodsremains gr1 WHERE gr1.pnt_as_key = gr.pnt_as_key AND gr1.accountDateGoods <= @END_DATE)
 LEFT OUTER JOIN Maindatabase.dbo.tbsort sort ON goods.idsort = sort.idsort
 LEFT OUTER JOIN Maindatabase.dbo.sprediz sed ON sed.edizid = goods.edizid
 WHERE dc.kodskl = @CODE_WAREHOUSE
END
ELSE
BEGIN
 SELECT DISTINCT goods.code_gr AS code_gr,goods.code_subgr AS code_subgr,goods.code_assort AS code_assortment,
 ds.pnt_as_key AS pnt_as_key,RTRIM(goods.namet) + ' ' + COALESCE(NULLIF(goods.sort,'б/с'),'') 
 + ' ' + COALESCE(NULLIF(CAST(goods.vlajn AS VARCHAR(12)),'0.00'),'') 
 + ' ' + COALESCE(NULLIF(CAST(goods.jirn AS VARCHAR(12)),'0.00'),'') AS name,sed.shortnameedizm AS unit,
 COALESCE(NULLIF(gr.remains,NULL),0) remains, 
 COALESCE(NULLIF(gr.avr_price,NULL),0) price, gr.accountDateGoods,
 CASE goods.code_gr WHEN 93 THEN 1 WHEN 99 THEN 1 ELSE 0 END AS PACKAGE_BOOL 
 FROM Maindatabase.dbo.docstring ds 
 INNER JOIN Maindatabase.dbo.doccaption dc ON ds.iddoc = dc.iddoc 
 AND dc.numotch IS NOT NULL AND dc.datedoc <= @END_DATE 
 INNER JOIN technolog.dbo.tbgoods goods ON goods.id = ds.pnt_as_key
 LEFT OUTER JOIN technolog.dbo.tbgoodsremains gr ON ds.pnt_as_key = gr.pnt_as_key AND
 gr.pnt_as_key = goods.id AND gr.accountDateGoods = ( SELECT MAX(gr1.accountDateGoods)
 FROM technolog.dbo.tbgoodsremains gr1 WHERE gr1.pnt_as_key = gr.pnt_as_key AND gr1.accountDateGoods <= @END_DATE)
 LEFT OUTER JOIN Maindatabase.dbo.tbsort sort ON goods.idsort = sort.idsort
 LEFT OUTER JOIN Maindatabase.dbo.sprediz sed ON (sed.edizid = goods.edizid)
 WHERE dc.kodskl = @CODE_WAREHOUSE	
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.saveRemainsAvrPrice 
@PNT_AS_KEY INT,
@PRISE DECIMAL(8,2),
@REMAINS DECIMAL(8,2),
@ENDDATE DATETIME,
@CODE_WAREHOUSE INT
AS
SET NOCOUNT ON
--START
DECLARE @ARRIVED_SUM DECIMAL(10,2)
SET @ARRIVED_SUM = @REMAINS* @PRISE
IF EXISTS(SELECT pnt_as_key FROM technolog.dbo.tbgoodsremains WHERE pnt_as_key = @PNT_AS_KEY AND code_warehouse = @CODE_WAREHOUSE AND accountDateGoods = @ENDDATE)
BEGIN
     UPDATE  technolog.dbo.tbgoodsremains SET remains = @REMAINS, avr_price = @PRISE,arrived_amount =  @REMAINS, arrived_sum = @ARRIVED_SUM,status = 1 
     WHERE pnt_as_key = @PNT_AS_KEY AND accountDateGoods = @ENDDATE AND code_warehouse = @CODE_WAREHOUSE
END
ELSE
BEGIN
     INSERT INTO technolog.dbo.tbgoodsremains(pnt_as_key,accountdategoods,code_warehouse,remains,avr_price,arrived_amount,arrived_sum,status) 
     VALUES (@PNT_AS_KEY, @ENDDATE,@CODE_WAREHOUSE,@REMAINS,@PRISE,@REMAINS,@ARRIVED_SUM,1)
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.insDocString
@IdDoc INT,
@PNT INT,
@KolF FLOAT, 
@CenO FLOAT,
@CenAvg FLOAT,
@KodSkl INT,
@IdGrOper SMALLINT,
@NDS FLOAT,
@NalTr FLOAT,
@SkidPost FLOAT,
@NacPosr FLOAT,
@NacOpt FLOAT,
@SkidPokup FLOAT,
@NacObpit FLOAT,
@CenPriobr FLOAT,
@DateDoc DATETIME = NULL,
@CODE_WAREHOUSE INT = NULL
AS
IF @NDS  IS NULL
  SET @NDS  = 0
IF @NalTr IS NULL
  SET @NalTr  = 0
IF @SkidPost IS NULL
  SET @SkidPost = 0
IF @NacPosr IS NULL
  SET @NacPosr = 0
IF @NacOpt IS NULL
  SET @NacOpt = 0
IF @SkidPokup IS NULL
  SET @SkidPokup = 0
IF @NacObpit IS NULL
  SET @NacObpit = 0
IF @CenPriobr  IS NULL
  SET @CenPriobr  = 0 
DECLARE @NameVidSyrie VARCHAR(50)
DECLARE @ToDate DATETIME
SET @NameVidSyrie = (SELECT Rtrim(v.NameVid) + space(2) + IsNull(t.NameTov,'')
FROM maindatabase.dbo.SprTovar t INNER JOIN 
maindatabase.dbo.SprVid v ON t.KodGr = v.KodGr AND t.KodPGr = v.KodPGr AND t.KodVid = v.KodVid WHERE t.PNT = @PNT)
--
DECLARE @NAMET VARCHAR(90)
DECLARE @SORT CHAR(3)
DECLARE @VLAJN DECIMAL(5,2)
DECLARE @JIRN DECIMAL(5,2)
DECLARE @KODGR INT
DECLARE @CODE_SUBGR INT
DECLARE @CODE_ASSORT INT
DECLARE @CODE_RAZ1 INT
DECLARE @CODE_RAZ2 INT
DECLARE @ED_IZ INT
DECLARE @SORT_ID INT
DECLARE @NAMETOV VARCHAR(30)

SELECT  DISTINCT @KODGR = st.kodgr, @CODE_SUBGR =  st.kodpgr,@CODE_ASSORT =  st.kodvid,
@CODE_RAZ1 = st.KodR1,  @CODE_RAZ2 = st.KodR2,@ED_IZ =  st.edizid, 
@NAMET = st.namet, @VLAJN = COALESCE(st.vlajn,NULL), @JIRN = COALESCE(st.jirn,NULL), @NAMETOV = st.nametov,
@SORT_ID = st.idsort,
@SORT = CASE COALESCE(st.idsort,0) WHEN 0 THEN NULL ELSE ts.namesort END 
FROM maindatabase.dbo.sprtovar st INNER JOIN maindatabase.dbo.tbsort ts 
ON  st.pnt = @PNT AND (st.idsort = ts.idsort OR st.idsort IS NULL)
IF (@SORT IS NULL)
  SET @SORT = ''
IF (@VLAJN IS NULL)
  SET @VLAJN = 0
IF (@JIRN IS NULL)
  SET @JIRN = 0
DECLARE @PNT_AS_KEY INT
SELECT @PNT_AS_KEY = ISNULL(MIN(ID),0) FROM Technolog.dbo.tbGoods 
WHERE code_gr = @KODGR AND code_subgr = @CODE_SUBGR AND code_assort = @CODE_ASSORT AND code_raz1 = @CODE_RAZ1 
AND code_raz2 = @CODE_RAZ2 AND nametov = @NAMETOV AND sort = @SORT AND vlajn = COALESCE(@VLAJN,0) AND jirn = COALESCE(@JIRN,0)
BEGIN TRANSACTION
IF @PNT_AS_KEY = 0
BEGIN
    INSERT INTO Technolog.dbo.tbGoods  (code_gr,code_subgr,code_assort,code_raz1,code_raz2,namet,sort,vlajn,jirn,idsort,edizid,nametov) 
    VALUES (@KODGR, @CODE_SUBGR,@CODE_ASSORT,@CODE_RAZ1,@CODE_RAZ2,@NAMET,@SORT,@VLAJN,@JIRN,@SORT_ID,@ED_IZ, @NAMETOV)
    IF @@ERROR <> 0
    BEGIN
       ROLLBACK TRANSACTION
       RETURN
    END
    SET @PNT_AS_KEY = @@IDENTITY	
    DECLARE @CODE_ARRIVED_OUT INT
    DECLARE @CODE_LEFT_OUT INT
    DECLARE @CODE_ARRIVED_IN INT
    DECLARE @CODE_LEFT_IN INT
    DECLARE @CODE_REMAINS INT
    EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
    @CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
    IF @IdGrOper =  @CODE_REMAINS
    BEGIN
	EXEC dbo.saveRemainsAvrPrice @PNT_AS_KEY, @CENO, @KOLF,@DATEDOC,@CODE_WAREHOUSE
             IF @@ERROR <> 0
             BEGIN
                ROLLBACK TRANSACTION
             RETURN
    END
    END
END

DECLARE @ID_STR INT
INSERT INTO maindatabase.dbo.DocString
  (IdDoc, NameVidTov, PNT, KolF, CenO,pnt_as_key, nds, naltr, skidpost, nacposr, nacopt, SkidPokup, NacObpit, cenpriobr)
VALUES
  (@IdDoc, @NameVidSyrie, @PNT, @KolF, @CenO, @PNT_AS_KEY,@NDS,@NalTr,@SkidPost,@NacPosr,@NacOpt, @SkidPokup, @NacObpit,@CenPriobr)
IF @@ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
RETURN
END
COMMIT TRANSACTION
SET @ID_STR = @@IDENTITY
SELECT ds.IdStr, ds.PNT, dbo.GetNameSyrie(ds.PNT) AS NameSyrie, ds.CenO, ds.CenRoz,
                   e.EdIz, ds.idDoc, t.Sertif, t.KodGr,ds.naltr,ds.skidpost,ds.nacposr,ds.nacobpit,ds.skidpokup,ds.nds,ds.nacopt,ISNULL(ds.cenpriobr,0) AS cenpriobr,ds.pnt_as_key
FROM  maindatabase.dbo.DocString ds INNER JOIN
                              maindatabase.dbo.SprTovar t ON t.PNT = ds.PNT LEFT OUTER JOIN
                              maindatabase.dbo.SprEdIz e ON e.EdIzID = t.EdIzID 
WHERE   (ds.IdStr = @ID_STR)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[insFactRecCaption]
@Vyhod float, 
@IdNormRec int, 
@DateDoc datetime
 AS
INSERT INTO dbo.tbFactRecCaption
                      (Vyhod, IdNormRec, DateDoc)
VALUES     (@Vyhod, @IdNormRec, @DateDoc);
                          SELECT     fc.Vyhod, fc.IdFactRec, fc.IdNormRec, nc.NumDoc, fc.DateDoc, nc.PNT, dbo.GetTovName(nc.PNT) AS NameTov, 
                                              e.EdIz, nc.Fasov, nc.NormVyhoda
                           FROM         dbo.tbFactRecCaption fc INNER JOIN
                                                  dbo.tbNormRecCaption nc ON fc.IdNormRec = nc.IdNormRec INNER JOIN
                                                  MainDataBase.dbo.SprTovar t ON t .PNT = nc.PNT LEFT OUTER JOIN
                                                  MainDataBase.dbo.SprEdIz e ON e.EdIzID = t .EdIzID
                           WHERE     (IdFactRec = @@IDENTITY)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[insFactRecString] 
@IdFactRec int,
@PNT int, 
@Rash float, 
@IdPriznSyria int, 
@PriznakCalcWater bit, 
@Data float
AS
INSERT INTO dbo.tbFactRecString
                      (IdFactRec, PNT, Rash, IdPriznSyria, PriznakCalcWater, Data)
VALUES     (@IdFactRec, @PNT, @Rash, @IdPriznSyria, @PriznakCalcWater, @Data);
                          SELECT     fs.IdFactStr, fs.IdFactRec, fs.PNT, dbo.GetTovName(fs.PNT) AS NameTov, fs.Rash, fs.IdPriznSyria, e.EdIz, ps.NamePriznSyria, 
                                                  fs.PriznakCalcWater
                           FROM         dbo.tbFactRecString fs INNER JOIN
                                                  MainDataBase.dbo.SprTovar t ON t .PNT = fs.PNT INNER JOIN
                                                  MainDataBase.dbo.SprPriznSyria ps ON ps.IDPriznSyria = fs.IdPriznSyria LEFT OUTER JOIN
                                                  MainDataBase.dbo.SprEdIz e ON e.EdIzID = t .EdIzID
                           WHERE     (IdFactStr = @@IDENTITY)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROCEDURE dbo.insMol
@TABN INT,
@PROF SMALLINT,
@FIO VARCHAR(45),
@MAT_OTV BIT = 0
AS
INSERT INTO maindatabase.dbo.spr_works (tabn,profes,mat_otv,fio) VALUES(@TABN,@PROF,@MAT_OTV,@FIO)



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.insPriznSyria
(
	@NamePriznSyria varchar(30)
)
AS
	SET NOCOUNT OFF;
INSERT INTO MainDataBase.dbo.SprPriznSyria(NamePriznSyria) VALUES (@NamePriznSyria)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[insProduction]
  @KodGr tinyint,
  @KodPGr tinyint, 
  @KodVid tinyint, 
  @KodR1 tinyint, 
  @KodR2 tinyint, 
  @CenO decimal(18,3),
  @NameTov varchar(30), 
  @IdSort tinyint,
  @EdIzID smallint, 
  @PriznSyria varchar(50),
  @DatePrih datetime,
  @SrokGodn varchar(16),
  @Sertif  varchar(255), 
  @VidUp char(5),
  @MinUp decimal(7,3), 
  @Fasov decimal(7,3), 
  @Art  varchar(30), 
  @Vlajn decimal(5,2),
  @Jirn decimal(5,2),
  @IdPredpr int,
  @IdCountry smallint,
  @PNTTar1 int,
  @PNTTar2 int,
  @Ves decimal(7,2),
  @NDS decimal(5,2), 
  @IdPriznNac tinyint, 
  @IdEnterprise int,
  @PrSyrja TINYINT	
AS
INSERT INTO MainDataBase.dbo.SprTovar
           (KodGr, 
            KodPGr, 
            KodVid, 
            KodR1, 
            KodR2, 
            NameTov, 
            IdSort,
            EdIzID,  
            PriznSyria, 
            DatePrih,
            SrokGodn,
            Sertif, 
            VidUp, 
            MinUp, 
            Fasov,
            Art, 
            Vlajn, 
            Jirn, 
            IdPredpr, 
            IdCountry, 
            PNTTar1, 
            PNTTar2,
            Ves, 
            CenO, 
            NDS, 
            IdPriznNac,
            PrSyrja)
VALUES (@KodGr, 
            @KodPGr, 
            @KodVid, 
            @KodR1, 
            @KodR2, 
            @NameTov, 
            @IdSort,
            @EdIzID,  
            @PriznSyria, 
            @DatePrih,
            @SrokGodn, 
            @Sertif, 
            @VidUp, 
            @MinUp, 
            @Fasov,
            @Art, 
            @Vlajn, 
            @Jirn, 
            @IdPredpr, 
            @IdCountry, 
            @PNTTar1, 
            @PNTTar2,
            @Ves, 
            @CenO, 
            @NDS, 
            @IdPriznNac,
            @PrSyrja);
DECLARE @NewPNT INT;
SET @NewPNT = @@IDENTITY;
INSERT INTO dbo.tbProd
           (PNT, IdEnterprise)
VALUES     (@NewPNT, @IdEnterprise);
 
SELECT st.PNT, st.KodGr, st.KodPGr, st.KodVid, 
       st.KodR1, st.KodR2, 0 AS Ostatok, st.CenO, 
       st.NameT, st.NameTov, ss.NameSort, st.IdSort, 
       ei.EdIz, st.EdIzID, st.PriznSyria, st.DatePrih, 
       st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, 
       st.Art, st.Vlajn, st.Jirn, st.IdPredpr, st.IdCountry, 
       st.PNTTar1, st.PNTTar2, st.Ves, st.NDS, st.IdPriznNac, 
       st.PrSyrja, p.IdEnterprise
FROM   MainDatabase.dbo.SprTovar st LEFT OUTER JOIN
       MainDatabase.dbo.tbPriznNac pn ON st.IdPriznNac = pn.IdPriznNac LEFT OUTER JOIN
       MainDatabase.dbo.SprEdIz ei ON ei.EdIzID = st.EdIzID LEFT OUTER JOIN
       MainDatabase.dbo.tbSort ss ON ss.IdSort = st.IdSort INNER JOIN
       tbProd p ON st.PNT = p.PNT
WHERE  (p.IdEnterprise = @IdEnterprise) and (st.PNT = @NewPNT)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE [dbo].[insSyrie]
 @KodGr tinyint,
 @KodPGr tinyint, 
 @KodVid tinyint, 
 @KodR1 tinyint, 
 @KodR2 tinyint, 
 @NameT varchar(90), 
 @NameTov varchar(30), 
 @EdIzID smallint, 
 @IdSort tinyint,
-- @PriznSyria varchar(50),
 @PrSyrja tinyint,
 @DatePrih datetime,
 @SrokGodn varchar(10),
 @Sertif  varchar(255), 
 @VidUp char(5),
 @MinUp decimal(7,3), 
 @Fasov decimal(7,3), 
 @Art  varchar(30), 
 @Vlajn decimal(5,2),
 @Jirn decimal(5,2),
 @IdPredpr int,
 @IdCountry smallint,
 @PNTTar1 int,
 @PNTTar2 int,
 @Ves decimal(7,2),
 @CenO decimal(18,3),
 @NDS decimal(5,2), 
 @IdPriznNac tinyint, 
 @IdEnterprise int,
 @NalTr DECIMAL(18,3) = NULL,
 @SkidPost DECIMAL(18,3) = NULL,
 @NacPosr DECIMAL(18,3) = NULL,
 @CenPriobr DECIMAL(18,3) = NULL,
 @InsTbSyrie BIT = NULL

 AS
BEGIN TRAN
SET  @InsTbSyrie = 0 
INSERT INTO MainDataBase.dbo.SprTovar
                (KodGr, KodPGr, KodVid, KodR1, KodR2, NameT, NameTov, EdIzID, IdSort,  PrSyrja, DatePrih,
                 SrokGodn, Sertif, VidUp, MinUp, Fasov,Art, Vlajn, Jirn, IdPredpr, IdCountry , PNTTar1, PNTTar2,
                 Ves, CenO, NDS, IdPriznNac,NalTr,SkidPost,NacPosr,CenPriobr)
VALUES  (@KodGr, @KodPGr, @KodVid, @KodR1, @KodR2, @NameT, @NameTov,  @EdIzID, @IdSort,  @PrSyrja, @DatePrih, 
                 @SrokGodn, @Sertif, @VidUp, @MinUp, @Fasov,@Art, @Vlajn, @Jirn, @IdPredpr, @IdCountry , @PNTTar1, @PNTTar2, 
                 @Ves, @CenO, @NDS, @IdPriznNac,@NalTr,@SkidPost,@NacPosr, @CenPriobr)
IF @@ERROR <> 0
BEGIN
  ROLLBACK TRANSACTION
  RETURN
END

DECLARE @NewPNT INT
SET @NewPNT = @@IDENTITY
IF  @InsTbSyrie IS NOT NULL
BEGIN
  INSERT INTO dbo.tbSyrie(PNT, IdEnterprise) VALUES     (@NewPNT, @IdEnterprise)
  IF @@ERROR <> 0
  BEGIN
     ROLLBACK TRANSACTION
    RETURN
  END
END
COMMIT TRAN
 
SELECT  st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, st.PNT, st.NameT, st.NameTov ,st.EdIzID,st.IdSort, st.PrSyrja, 
                st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, st.Vlajn, st.Jirn, st.IdPredpr,st.IdCountry , 
                st.PNTTar1, st.PNTTar2, st.Ves, st.CenO,st.NDS, e.EdIz, s.NameSort,  syr.IdEnterprise,NalTr,st.SkidPost,st.NacPosr,st.cenpriobr
 FROM         MainDataBase.dbo.SprTovar st LEFT OUTER JOIN
                    MainDataBase.dbo.tbSort s ON s.IdSort = st.IdSort LEFT OUTER JOIN
                    MainDataBase.dbo.SprEdIz e ON e.EdIzID = st.EdIzID INNER JOIN
                    dbo.tbSyrie syr ON syr.PNT = st.PNT
 WHERE     (syr.IdEnterprise = @IdEnterprise) and (syr.PNT = @@IDENTITY)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.inssDocCaption
@DateDoc datetime, 
@NumDoc int, 
@VidDoc tinyint,
@KodSkl int,
@IdGrOper int, 
@NumOtch int, 
@DateOtch datetime, 
@IdPredpr int
AS
DECLARE @CODE_REMAINS INT
SELECT @CODE_REMAINS = REMAINS FROM technolog.dbo.gropersettings
IF @CODE_REMAINS = @IdGrOper
BEGIN
	SET @NumOtch = -1
END
INSERT INTO maindatabase.dbo.DocCaption
  (DateDoc, NumDoc, VidDoc, KodSkl, IdGrOper, NumOtch, DateOtch, IdPredpr)
VALUES
  (@DateDoc, @NumDoc, @VidDoc, @KodSkl, @IdGrOper, @NumOtch, @DateOtch, @IdPredpr)
   
       SELECT   dc.NumDoc, dc.DateDoc, dc.NumOtch, dc.DateOtch, pr.namePredprShort, 
                    dc.IdPredpr, dc.KodSkl, dc.VidDoc
            FROM    maindatabase.dbo.DocCaption dc INNER JOIN
                    maindatabase.dbo.tbPredpr pr ON dc.IdPredpr = pr.idPredpr
           WHERE     (IdDoc = @@IDENTITY)
RETURN (@@IDENTITY)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.reportRawMaterial
@KodSkl int,
@Groups varchar(5000)
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
--END
DECLARE @Cmd varchar(5000)
DECLARE @Skl varchar(500)
DECLARE @Enterprise varchar(500)
	SELECT  v.kodgr,v.kodpgr,v.kodvid,v.kodr1,v.kodr2,v.namet,v.sort as namesort,v.vlajn,v.jirn,v.ceno,v.sertif,v.pnt,(v.ARRIVED_OUTSIDE+ARRIVED_INSIDE-v.LEFT_OUTSIDE-LEFT_INSIDE) AS TOTAL FROM(
	SELECT  max(st.KodGr) as kodgr, max(st.KodPGr) as kodpgr, max(st.KodVid) as kodvid, max(st.KodR1) as kodr1, max(st.KodR2) as kodr2,
	MAX(ds.idstr) AS idstr, min(goods.namet) AS namet, min(goods.sort) AS sort, min(goods.vlajn) AS vlajn, min(goods.jirn) AS jirn, max(ds.ceno) as ceno,max(st.sertif) as sertif,max(ds.pnt) as pnt,
	SUM (CASE dc.viddoc WHEN 1 THEN (CASE dc.idgroper WHEN @CODE_ARRIVED_OUT THEN ds.kolf WHEN @CODE_REMAINS THEN ds.kolf ELSE 0 END) ELSE 0 END) AS ARRIVED_OUTSIDE,
	SUM (CASE dc.viddoc WHEN 2 THEN (CASE dc.idgroper WHEN @CODE_LEFT_OUT THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_OUTSIDE,
	SUM (CASE dc.viddoc WHEN 1 THEN (CASE dc.idgroper WHEN @CODE_ARRIVED_IN THEN ds.kolf ELSE 0 END) ELSE 0 END) AS ARRIVED_INSIDE,
	SUM (CASE dc.viddoc WHEN 2 THEN (CASE dc.idgroper WHEN @CODE_LEFT_IN THEN ds.kolf ELSE 0 END) ELSE 0 END) AS LEFT_INSIDE
	FROM MainDatabase.dbo.docstring ds 
	INNER JOIN MainDatabase.dbo.doccaption dc ON dc.iddoc = ds.iddoc AND dc.idgroper 
	IN (@CODE_REMAINS,@CODE_ARRIVED_OUT,@CODE_LEFT_OUT,@CODE_ARRIVED_IN,@CODE_LEFT_IN) AND dc.kodskl = @KodSkl
	INNER JOIN MainDatabase.dbo.tbgroper grop ON grop.idgroper = dc.idgroper 
	INNER JOIN MainDatabase.dbo.SprTovar st ON ds.pnt = st.pnt
	INNER JOIN technolog.dbo.tbgoods goods ON goods.id = ds.pnt_as_key	
	GROUP BY ds.pnt_as_key) v
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.saveAccount
@CODE_WAREHOUSE INT,
@NDS_1 DECIMAL(10,2),
@NDS_2 DECIMAL(10,2),
@ACCOUNT_NAME VARCHAR(10),
@ACCOUNT_VALUE INT
AS
BEGIN TRANSACTION
IF EXISTS (SELECT * FROM maindatabase.dbo.tbNastrSchet WHERE idpredpr =  @CODE_WAREHOUSE)
BEGIN
  UPDATE maindatabase.dbo.tbNastrSchet SET OsnSchet = @ACCOUNT_NAME, idschetsubschet = @ACCOUNT_VALUE  WHERE idPredpr =  @CODE_WAREHOUSE
END
ELSE
BEGIN
  INSERT INTO maindatabase.dbo.tbNastrSchet VALUES (@CODE_WAREHOUSE, @ACCOUNT_VALUE, @ACCOUNT_NAME)
END

IF @@ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
END
TRUNCATE  TABLE   tbNDS
INSERT INTO tbNDS VALUES(@NDS_1)
INSERT INTO tbNDS VALUES(@NDS_2)
IF @@ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
END

COMMIT TRANSACTION
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.saveInvoice  
@ID_DOC INT,
@ISSUE_DATE SMALLDATETIME = '01/01/2006',
@NUM_INVOICE VARCHAR(15) = '',
@SERIES VARCHAR(15) = '',
@LETTER_OF_ATTORNEY VARCHAR(15) = '',
@ID_RECIPIENT INT = 0,
@RECIPIENT VARCHAR(50) = '',
@GOAL INT,
@GOAL_OF_PURCHASING VARCHAR(50) = '',
@ID_MOL INT,
@TYPE INT = 0,
@OWNERCAR VARCHAR(30) = '',
@DRIVER VARCHAR(30) = '',
@NUMBERCAR VARCHAR(12) = '',
@TYPE_TRANSPORT VARCHAR(12) =''
AS
IF @GOAL = -1
BEGIN
--  IF NOT EXISTS (SELECT goal FROM tbGoals WHERE goal = @GOAL_OF_PURCHASING)
--  BEGIN
	  INSERT INTO tbGoals(goal) VALUES(@GOAL_OF_PURCHASING)
	  SET @GOAL = @@IDENTITY 	
-- END
END
IF @ID_RECIPIENT = -1
BEGIN
--  IF NOT EXISTS (SELECT recipient FROM tbrecipient WHERE recipient = @RECIPIENT)
--  BEGIN
	  INSERT INTO tbrecipient(recipient) VALUES(@RECIPIENT)
	  SET @ID_RECIPIENT = @@IDENTITY 	
-- END 
END
INSERT INTO tbInvoiceIssue VALUES(@ID_DOC,@ISSUE_DATE,@NUM_INVOICE,@SERIES,@LETTER_OF_ATTORNEY,
@ID_RECIPIENT, @GOAL,@ID_MOL,@TYPE,@OWNERCAR,@DRIVER,@NUMBERCAR,@TYPE_TRANSPORT)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.selAccount
@BegDate datetime,
@EndDate datetime,
@KodSkl int
 AS
 SELECT DISTINCT dc.KodSkl, dbo.GetPredprName(@KodSkl) AS NameSkl, dc.NumOtch, dc.VidDoc, 
                       dc.DateOtch, dc.TabN, mol.fio 
     from maindatabase.dbo.DocCaption dc 
     INNER JOIN  maindatabase.dbo.tbMol mol ON mol.TabN= dc.TabN
  where (KodSkl=@KodSkl) and (DateOtch between @BegDate and @EndDate)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE selCalculatedData_BalanceSheet
@START_DATE DATETIME,
@END_DATE DATETIME,
@PNT_AS_KEY INT,
@CODE_WAREHOUSE INT,
@AVR_PRICE DECIMAL(10,2) = 0 OUTPUT
AS
SET NOCOUNT ON
SELECT ISNULL(SUM(arrived_amount),0) AS arrived_amount, ISNULL(SUM(arrived_sum),0) AS arrived_sum, ISNULL(SUM(left_amount),0) AS left_amount,ISNULL(SUM(left_sum),0) AS left_sum 
FROM tbgoodsremains WHERE pnt_as_key = @PNT_AS_KEY AND accountdategoods > @START_DATE 
AND code_warehouse = @CODE_WAREHOUSE AND accountdategoods <= @END_DATE
--DECLARE @MONTH INT
--SET @MONTH = MONTH(@START_DATE)
--SELECT @AVR_PRICE = MAX(avr_price) FROM tbgoodsremains WHERE pnt_as_key = @PNT_AS_KEY 
--AND code_warehouse = @CODE_WAREHOUSE AND MONTH(accountdategoods) = @MONTH

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.selDocCaption
@KodSkl INT,
@VidDoc TINYINT,
@IdGrOper SMALLINT,
@BegDate DATETIME,
@EndDate DATETIME,
@ValueOut INT OUTPUT
AS
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
--END
SET @ValueOut = 0
IF @IdGrOper =  @CODE_ARRIVED_OUT
BEGIN
	SET @ValueOut = 1
END
IF @IdGrOper =  @CODE_LEFT_OUT 
BEGIN
	SET @ValueOut = 2
END
--IF @IdGrOper =  @CODE_ARRIVED_IN 
IF @IdGrOper NOT IN (@CODE_ARRIVED_OUT,@CODE_REMAINS) AND @VidDoc = 1
BEGIN
	SET @ValueOut = 3
END
--IF @IdGrOper =  @CODE_LEFT_IN 
IF @IdGrOper NOT IN(@CODE_LEFT_OUT,@CODE_REMAINS) AND @VidDoc = 2
BEGIN
	SET @ValueOut = 4
END
	
select  dc.IdDoc, dc.NumDoc, dc.DateDoc, dc.IdGrOper, dc.NumOtch, dc.DateOtch, 
           pr.namePredprShort, dc.IdPredpr, dc.KodSkl, dc.VidDoc,
           dc.Itogo, dc.ItogoTov, dc.ItogoTar, dc.ItogoTovR, dc.ItogoTarR
FROM  maindatabase.dbo.DocCaption dc INNER JOIN
              maindatabase.dbo.tbPredpr pr ON dc.IdPredpr = pr.idPredpr
where dc.KodSkl = @KodSkl and dc.VidDoc = @VidDoc and dc.IdGrOper = @IdGrOper
 and dc.DateDoc between @BegDate and @EndDate
 order by dc.NumDoc

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.selDocOfAccount
 @BegDate datetime,
 @EndDate datetime,
 @KodSkl int
 AS
 select distinct dc.IdDoc, dc.NumDoc, dc.DateDoc, dc.IdPredpr, dc.KodSkl, dc.NumOtch, dc.VidDoc, dc.DateOtch,
          dc.ItogoTov, dc.ItogoTar, dc.TabN, mol.fio, pr.NamePredpr, IsNULL(pr.KodPredpr,0) AS KodPredpr
     from maindatabase.dbo.DocCaption dc 
     INNER JOIN  maindatabase.dbo.tbMol mol ON mol.TabN = dc.TabN
     INNER JOIN maindatabase.dbo.tbPredpr pr ON pr.IdPredpr = dc.IdPredpr
     WHERE (KodSkl=@KodSkl) and (DateOtch between @BegDate and @EndDate)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.selDocString
@KodSkl INT,
@VidDoc TINYINT,
@IdGrOper SMALLINT,
@BegDate DATETIME,
@EndDate DATETIME
AS
SELECT ds.IdStr, ds.PNT, dbo.GetNameSyrie(ds.PNT) AS NameSyrie, ds.KolF, ds.CenO,
         ds.CenRoz, e.EdIz, ds.IdDoc,ds.nds,ds.naltr,ds.skidpost,ds.nacposr,ds.nacobpit,ds.skidpokup,ds.nacopt,t.Sertif, t.KodGr --,ds.pnt_as_key
           FROM maindatabase.dbo.DocString ds INNER JOIN
                        maindatabase.dbo.DocCaption dc ON ds.IdDoc = dc.IdDoc INNER JOIN
                        maindatabase.dbo.SprTovar t ON t.PNT = ds.PNT LEFT OUTER JOIN
                        maindatabase.dbo.SprEdIz e ON e.EdIzID = t.EdIzID 
           WHERE   dc.KodSkl = @KodSkl AND dc.VidDoc = @VidDoc AND 
                   dc.IdGrOper = @IdGrOper  AND dc.DateDoc BETWEEN @BegDate AND @EndDate 
           ORDER BY ds.IdStr

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.selFactRecCaption 
@IdEnterprise tinyint,
@BegDate datetime,
@EndDate datetime
AS
SELECT     fc.IdFactRec, fc.IdNormRec, nc.NumDoc, fc.DateDoc, nc.PNT, dbo.GetTovName(nc.PNT) AS NameTov, e.EdIz, 
           nc.Fasov, fc.Vyhod, nc.NormVyhoda 
FROM         dbo.tbFactRecCaption fc INNER JOIN
                      dbo.tbNormRecCaption nc ON fc.IdNormRec = nc.IdNormRec INNER JOIN
                      MainDataBase.dbo.SprTovar t ON t.PNT = nc.PNT LEFT OUTER JOIN
                      MainDataBase.dbo.SprEdIz e ON e.EdIzID = t.EdIzID
WHERE     (nc.IdEnterprise = @IdEnterprise) AND (fc.DateDoc BETWEEN @BegDate AND @EndDate)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[selFactRecString]
@IdMetodOcenki int,
@KodSkl int,
@Date datetime,
@BegDate  datetime,
@EndDate datetime
 AS
SELECT     fs.IdFactStr, fs.IdFactRec, fs.PNT, dbo.GetTovName(fs.PNT) AS NameTov, fs.Rash, fs.IdPriznSyria, e.EdIz, ps.NamePriznSyria, fs.PriznakCalcWater, 
                      fs.Data, s.NameSort, t .KodGr, dbo.GetOstatok(@IdMetodOcenki, @KodSkl, fs.PNT, @Date) AS Ostatok, dbo.GetCena(@IdMetodOcenki, @KodSkl, 
                      fs.PNT, @Date) AS Cena
FROM         dbo.tbFactRecString fs INNER JOIN
                      dbo.tbFactRecCaption fc ON fc.IdFactRec = fs.IdFactRec INNER JOIN
                      MainDataBase.dbo.SprTovar t ON t .PNT = fs.PNT INNER JOIN
                      MainDataBase.dbo.SprPriznSyria ps ON ps.IDPriznSyria = fs.IdPriznSyria LEFT OUTER JOIN
                      MainDataBase.dbo.SprEdIz e ON e.EdIzID = t .EdIzID LEFT OUTER JOIN
                      MainDataBase.dbo.tbSort s ON s.IdSort = t .IdSort
WHERE     fs.IdPriznSyria <> 0 AND (fc.DateDoc BETWEEN @BegDate AND @EndDate)
UNION
SELECT     fs.IdFactStr, fs.IdFactRec, fs.PNT, er.NameElRec AS NameTov, fs.Rash, fs.IdPriznSyria, e.EdIz, 'Элемент рецептуры' AS NamePriznSyria, 
                      fs.PriznakCalcWater, NULL AS Data, '' AS NameSort, 0 AS KodGr, NULL AS Ostatok, NULL AS Cena
FROM         dbo.tbFactRecString fs INNER JOIN
                      dbo.tbFactRecCaption fc ON fc.IdFactRec = fs.IdFactRec INNER JOIN
                      dbo.tbElReception er ON fs.PNT = er.IdElRec LEFT OUTER JOIN
                      MainDataBase.dbo.SprEdIz e ON e.EdIzID = er.EdIzID
WHERE     fs.IdPriznSyria = 0 AND (fc.DateDoc BETWEEN @BegDate AND @EndDate)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.selMol
 AS
SELECT sw.tabn,sw.fio,sw.profes AS profes,sw.kodmol,sw.mat_otv FROM maindatabase.dbo.spr_works sw
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.selPriznSyria
AS
	SET NOCOUNT ON;
SELECT IDPriznSyria, NamePriznSyria FROM MainDataBase.dbo.SprPriznSyria

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.selProduction 
@IdEnterprise INT
AS
SELECT     st.PNT, st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, 0 AS Ostatok, st.CenO, st.NameT, st.NameTov, ss.NameSort, st.IdSort, ei.EdIz, st.EdIzID, 
                      st.PriznSyria, st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, st.Vlajn, st.Jirn, st.IdPredpr, st.IdCountry, st.PNTTar1, st.PNTTar2, 
                      st.Ves, st.NDS, st.IdPriznNac, st.PrSyrja, p.IdEnterprise, pn.NamePriznNac
FROM         MainDataBase.dbo.SprTovar st LEFT OUTER JOIN
                      MainDataBase.dbo.tbPriznNac pn ON st.IdPriznNac = pn.IdPriznNac LEFT OUTER JOIN
                      MainDataBase.dbo.SprEdIz ei ON ei.EdIzID = st.EdIzID LEFT OUTER JOIN
                      MainDataBase.dbo.tbSort ss ON ss.IdSort = st.IdSort INNER JOIN
                      tbProd p ON st.PNT = p.PNT
WHERE     (p.IdEnterprise = @IdEnterprise)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


CREATE PROCEDURE dbo.selectRawMaterialByGroupsTest
@Groups VARCHAR(1000)
AS
SET NOCOUNT ON
DECLARE @Cmd VARCHAR(5000)
SET @Cmd =
 N'  SELECT st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, st.PNT, st.NameT, st.NameTov , st.EdIzID, st.IdSort, st.PriznSyria, 
                       st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, st.Vlajn, st.Jirn, st.IdPredpr,st.IdCountry , 
                       st.PNTTar1, st.PNTTar2, st.Ves, st.CenO, st.NDS, se.EdIz, srt.NameSort,  st.IdPriznNac 
          FROM MainDataBase.dbo.SprTovar st 
          LEFT OUTER JOIN  MainDataBase.dbo.SprEdIz se ON se.EdIzID = st.EdIzID and st.PriznSyria IS NOT NULL
          LEFT OUTER JOIN  MainDataBase.dbo.tbSort srt ON srt.IdSort = st.IdSort '
IF @Groups  != ''
BEGIN
SET @Cmd = @Cmd + ' AND  st.KodGr IN (' +  @Groups + ')'
--SET @Cmd = @Cmd +  @Groups
END
SET @Cmd = @Cmd + '  WHERE  st.PriznSyria IS NOT NULL'
--print @Cmd
EXEC (@Cmd)



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


CREATE PROCEDURE dbo.selectTemprRemainsRawMaterial 
@CODE_GR INT,
@CODE_SUBGR INT,
@CODE_ASSORTMENT INT
--@PNT_AS_KEY INT,
AS
 SET NOCOUNT ON
 SELECT CODE_GR,CODE_SUBGR, CODE_ASSORTMENT,PNT_AS_KEY,NAME, AMOUNT, AVR_PRICE, UNIT
 FROM ##RemainsSyrie WHERE CODE_GR = @CODE_GR AND CODE_SUBGR = @CODE_SUBGR AND CODE_ASSORTMENT = @CODE_ASSORTMENT



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[sp_syrCaptionPrint]
 @IdDoc int
 AS
declare @IdPred smallint,
             @KodSkl smallint,
             @UNNPlatPred varchar(20),
             @UNNPlatSkl varchar(20),
             @OKPOPlatPred varchar(20),
             @OKPOPlatSkl varchar(20),
             @LICPlatPred varchar(50),
             @LICPlatSkl varchar(50),
             @IdPlatPred smallint,
             @IdPlatSkl smallint,
             @NamePlatSkl varchar(50),
             @NamePlatPredpr varchar(50),
             @NamePred varchar(50),
             @NameSkl varchar(50),
             @FIODir varchar(30),
             @TownPred varchar(25),
             @StHoFlPred varchar(30),
             @StHoFlPlatPredpr varchar(30),
             @TownSkl varchar(25),
             @StHoFlSkl varchar(30),
             @RschetPlatPred varchar(30),
             @KodMFOPlatPred varchar(20),
             @IdBankPlatPred smallint,
             @BankPlatPred varchar(50),
             @TownBankPred varchar(25),
             @RschetPlatSkl varchar(30),
             @KodMFOPlatSkl varchar(20),
             @IdBankPlatSkl smallint,
             @BankPlatSkl varchar(50),
             @TownBankSkl varchar(25),
             @TownPlatSkl varchar(25),
             @TownPlatPredpr varchar(25),
             @PhonePlatSkl varchar(30),
             @PhonePlatPredpr varchar(30),
             @FaxPlatSkl varchar(30),
             @FaxPlatPredpr varchar(30), 
             @StHoFlPlatSkl varchar(30),
             @Dogov varchar(30),
             @FIOGlBuh varchar(30)
set @UNNPlatPred=''
set @OKPOPlatPred=''
set @IdPlatPred=0
set @UNNPlatSkl=''
set @OKPOPlatSkl=''
set @LICPlatPred=''
set @LICPlatSkl=''
set @IdPlatSkl=0
set @IdPlatPred=0
set @NamePlatSkl=''
set @NamePlatPredpr=''
set @NamePred=''
set @NameSkl=''
set @FioDir=''
set @TownPred=''
set @StHoFlPred=''
set @StHoFlPlatPredpr=''
set @TownPlatSkl=''
set @StHoFlPlatSkl=''
set @TownSkl=''
set @StHoFlSkl=''
set @RschetPlatPred=''
set @KodMFOPlatPred=''
set @IdBankPlatPred=0
set @BankPlatPred=''
set @TownBankPred=''
set @RschetPlatSkl=''
set @KodMFOPlatSkl=''
set @IdBankPlatSkl=0
set @TownBankSkl=''
set @PhonePlatSkl='' 
set @PhonePlatPredpr=''
set @FaxPlatSkl=''
set @FaxPlatPredpr=''
set @BankPlatSkl=''
set @Dogov=''
set @FIOGlBuh=''
select @IdPred = IdPredpr, @KodSkl = KodSkl from maindatabase.dbo.DocCaption
   where IdDoc = @IdDoc
--определяем УНН и ОКПО для плательщиков предприятия и склада
exec FindRekvizPlat @IdPred,@UNN=@UNNPlatPred output,
                                                @KodOKPO=@OKPOPlatPred output,@LIC=@LICPlatPred output,
                                                @IdPlat=@IdPlatPred output
exec FindRekvizPlat @KodSkl,@UNN=@UNNPlatSkl output,
                                                 @KodOKPO=@OKPOPlatSkl output,@LIC=@LICPlatSkl output,
                                                 @IdPlat=@IdPlatSkl output
-- наименования предприятия, склада и плательщика склада  
exec FindNamePredpr @IdPred,@NamePredprShort=@NamePred output
exec FindNamePredpr @KodSkl,@NamePredprShort=@NameSkl output
exec FindNamePredpr @IdPlatSkl,@NamePredprShort=@NamePlatSkl output
exec FindNamePredpr @IdPlatPred,@NamePredprShort=@NamePlatPredpr output
-- находим адрес предприятия,плательщика предприятия, тел. и факс плат.предприятия
exec FindNameTown @IdPred,@NameTown=@TownPred output
exec FindNameTown @IdPlatPred,@NameTown=@TownPlatPredpr output
exec FindStHoFl @IdPred,@StHoFl=@StHoFlPred output
exec FindStHoFl @IdPlatPred,@StHoFl=@StHoFlPlatPredpr output
exec FindPhoneFaxPredpr @IdPlatPred, @Phone=@PhonePlatPredpr output,
                                                                   @Fax=@FaxPlatPredpr output
--  договор , адрес склада 
exec FindDogovor @IdPred, @Dogovor=@Dogov output
exec FindNameTown @KodSkl,@NameTown=@TownSkl output
exec FindStHoFl @KodSkl,@StHoFl=@StHoFlSkl output
-- адрес плательщика склада, и фамилию директора
exec FindNameTown @idPlatSkl,@NameTown=@TownPlatSkl output
exec FindStHoFl @IdPlatSkl,@StHoFl=@StHoFlPlatSkl output
exec FindPhoneFaxPredpr @IdPlatSkl, @Phone=@PhonePlatSkl output,
                                                              @Fax=@FaxPlatSkl output
exec FindFlO @IdPlatSkl,@FIODir=@FIoDir output,@FIOGlBuh=@FIOGlBuh output
--находим р/счета и банки плательщиков предприятия и склада
exec FindRschetPlat @IdPlatPred,@Rschet=@RschetPlatPred output,
                                                @IdBank=@IdBankPlatPred  output,@KodMFO=@KodMFOPlatPred output
exec FindNamePredpr @IdBankPlatPred, @NamePredprShort=@BankPlatPred output
exec FindRschetPlat @KodSkl,@Rschet=@RschetPlatSkl output,
                                                  @IdBank=@IdBankPlatSkl  output,@KodMFO=@KodMFOPlatSkl output
exec FindNamePredpr @IdBankPlatSkl, @NamePredprShort=@BankPlatSkl output
-- города банков предприятия и склада
exec FindNameTown @IdBankPlatPred,@NameTown=@TownBankPred output
exec FindNameTown @IdBankPlatSkl ,@NameTown=@TownBankSkl output
if exists (select * from tempdb..sysobjects
           where name =  'tbSyrCaption')
           Drop table TEMPDB.DBO.tbSyrCaption
select
    @IdDoc as IdDoc,@idPred as IdPredpr, @KodSkl as KodSkl, ISNULL(@UNNPlatPred,'') as UNNPlatPred, 
    ISNULL(@OKPOPlatPred,'') as OKPOPlatPred, ISNULL(@UNNPlatSkl,'') as UNNPlatSkl,ISNULL(@OKPOPlatSkl,'') as OKPOPlatSkl,
    ISNULL(@LICPlatPred,'') as LICPlatPred,ISNULL(@LICPlatSkl,'') as LICPlatSkl, ISNULL(@NamePred,'') as NamePred,ISNULL(@NameSkl,'') as NameSkl, 
    ISNULL(@NamePlatSkl,'') as NamePlatSkl,ISNULL(@FioDir,'') as FioDir , ISNULL(@FIOGlBuh,'') as FIOGlBuh, ISNULL(@RschetPlatPred,'') as RschetPlatPred, 
    ISNULL(@TownPred,'') as TownPred, ISNULL(@StHoFlPred,'') as StHoFlPred, ISNULL(@TownPlatSkl,'') as TownPlatSkl, 
    ISNULL(@StHoFlPlatSkl,'')  as StHoFlPlatSkl, ISNULL(@PhonePlatSkl,'') as PhonePlatSkl ,ISNULL(@FaxPlatSkl,'') as FaxPlatSkl,
    ISNULL(@StHoFlPlatPredpr,'') as StHoFlPlatPredpr,ISNULL(@TownPlatPredpr,'') as TownPlatPredpr, ISNULL(@PhonePlatPredpr,'') as PhonePlatPredpr,
    ISNULL(@FaxPlatPredpr,'') as FaxPlatPredpr, ISNULL(@BankPlatPred,'') as BankPlatPred, ISNULL(@TownBankPred,'') as TownBankPred, 
    ISNULL(@RschetPlatSkl,'') as RschetPlatSkl, ISNULL(@BankPlatSkl,'') as BankPlatSkl, ISNULL(@TownBankSkl,'') as TownBankSkl,
    ISNULL(@Dogov,'') as Dogov,ISNULL(@NamePlatPredpr,'') as NamePlatPredpr,ISNULL(@KodMFOPlatPred,'') as KodMFOPlatPred, ISNULL(@KodMFOPlatSkl,'')  as KodMFOPlatSkl 
 into TEMPDB.dbo.tbSyrCaption

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[sp_syrDocPrint]
 @IdDoc int
 AS
 exec sp_syrCaptionPrint @IdDoc
 select * from TEMPDB.dbo.tbSyrCaption where IdDoc = @IdDoc

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.tchCalcWaterBegin
@IdFactRec int
AS
DECLARE @IdCalcWater int
SELECT @IdCalcWater = IdCalcWater FROM dbo.tbCalcWaterCaption WHERE IdFactRec = @IdFactRec
-- Проверка на существование записи 
IF @IdCalcWater IS NULL
BEGIN
	-- Внесение данных в шапку
	INSERT INTO dbo.tbCalcWaterCaption (IdFactRec,  VlajnTesta)
	VALUES (@IdFactRec, 42.5)
	-- Получение нового идентификатора
	SET @IdCalcWater = (SELECT SCOPE_IDENTITY())
END
ELSE
BEGIN
	-- Шапка без изменений, а строки удаляются
             DELETE FROM dbo.tbCalcWaterString WHERE IdCalcWater = @IdCalcWater
END
-- Внесение строк
INSERT INTO dbo.tbCalcWaterString 
SELECT @IdCalcWater AS IdCalcWater, frs.PNT AS PNT,  frs.Rash AS Rash,
               IsNULL(frs.Data, 0.0) AS Vlajn, (100 - IsNULL(frs.Data, 0.0)) AS SurPer, frs.Rash * ( 100 - IsNULL(frs.Data, 0.0) ) / 100 AS SuhMas
FROM dbo.tbFactRecString frs
WHERE IdFactRec = @IdFactRec AND IdPriznSyria <> 0 AND PriznakCalcWater = 1
-- Очистка рассчетной таблицы
DELETE FROM dbo.tbCalcWater
-- Заполнение рассчетной таблицы
INSERT INTO tbCalcWater
SELECT s.IdCalcWaterStr, dbo.GetTovName(s.PNT) AS NameTov, s.Rash, s.Vlajn, s.SuhPer, s.SuhMas
FROM dbo.tbCalcWaterString s
JOIN dbo.tbCalcWaterCaption c ON s.IdCalcWater = c.IdCalcWater
WHERE c.IdFactRec = @IdFactRec

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.tchCalcWaterEnd
AS
DECLARE @IdCalcWaterStr int
DECLARE @Vlajn float
DECLARE @SuhPer float
DECLARE @SuhMas float
-- Создание курсора
DECLARE crsCalcWater CURSOR STATIC
FOR
 SELECT IdCalcWaterStr, Vlajn, SuhPer, SuhMas
 FROM dbo.tbCalcWater
-- Открытие курсора
OPEN crsCalcWater
-- Перенос данных
FETCH NEXT
FROM crsCalcWater
INTO @IdCalcWaterStr, @Vlajn, @SuhPer, @SuhMas
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
	UPDATE dbo.tbCalcWaterString
	SET Vlajn = @Vlajn, SuhPer = @SuhPer, SuhMas = @SuhMas
	WHERE IdCalcWaterStr = @IdCalcWaterStr
	 FETCH NEXT
	 FROM crsCalcWater
	 INTO @IdCalcWaterStr, @Vlajn, @SuhPer, @SuhMas
END
-- Освобождение курсора
CLOSE crsCalcWater
DEALLOCATE crsCalcWater

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.tchCopyFactRecToProizvZadan
@IdProizvZadan int,
@IdFactRec int
AS
DECLARE @IdNewProizvZadanProduceCaption int
DECLARE @Kolich float
DECLARE @SumOS float
DECLARE @Vyhod float
DECLARE @Ves float
DECLARE @Fasov float
SELECT @SumOS = SUM(Rash) FROM dbo.tbFactRecString WHERE IdFactRec = @IdFactRec AND IdPriznSyria = 1
SELECT @Vyhod = Vyhod FROM dbo.tbFactRecCaption WHERE IdFactRec = @IdFactRec
SELECT @Fasov = Fasov 
FROM dbo.tbFactRecCaption frc
INNER JOIN dbo.tbNormRecCaption nrc ON nrc.IdNormRec = frc.IdNormRec
WHERE frc.IdFactRec = @IdFactRec
SET @Ves = @SumOS * @Vyhod / 100
SET @Kolich = @Ves / @Fasov
INSERT INTO dbo.tbProizvZadanProduceCaption
	    (IdProizvZadan, IdFactRec, Kolich)
	VALUES (@IdProizvZadan, @IdFactRec, @Kolich)
SET @IdNewProizvZadanProduceCaption = SCOPE_IDENTITY()
INSERT INTO dbo.tbProizvZadanProduceString (IdProizvZadanProduceCaption, PNT, Rash)
	SELECT @IdNewProizvZadanProduceCaption AS IdProizvZadanProduceCaption, PNT,  Rash 
	FROM dbo.tbFactRecString
	WHERE IdFactRec = @IdFactRec AND IdPriznSyria <> 0

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.tchCopyNormRecToFactRec
@IdNormRec int,
@Vyhod float,
@DateDoc datetime
 AS
DECLARE @IdFactRec int
-- Добавление в tbFactRecCaption
INSERT INTO dbo.tbFactRecCaption(IdNormRec,Vyhod, DateDoc)
VALUES (@IdNormRec, @Vyhod, @DateDoc)
SET @IdFactRec = (SELECT SCOPE_IDENTITY())
-- Добавление в tbFactRecString
INSERT INTO dbo.tbFactRecString(IdFactRec, PNT, Rash, IdPriznSyria, PriznakCalcWater)
(SELECT @IdFactRec AS IdFactRec, PNT, NormRash, IdPriznSyria, 1
 FROM dbo.tbNormRecString
 WHERE IdNormRec = @IdNormRec)
-- Получение идентификатора производства
DECLARE @IdEnterprise int
SELECT @IdEnterprise = IdEnterprise FROM dbo.tbNormRecCaption WHERE IdNormRec = @IdNormRec
IF @IdEnterprise = 1 -- для хлебного пр - ва
-- Добавление в поле данных Data необходимых значений для конкретного вида про - ва
UPDATE dbo.tbFactRecString
SET Data = 14.5 
WHERE IdFactRec = @IdFactRec AND IdPriznSyria = 1 -- только для основного сырья
-- Возвращение идентификатора новой фактической рецептуры
SELECT @IdFactRec AS IdFactRec

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.tchDuplicateNormRec
@IdNormRec int,
@PNT int,
@NumDoc int,
@DateDoc datetime,
@IdEnterprise int,
@NormVyhoda float,
@IdEdRasch int,
@Fasov float
AS
DECLARE @IdNewNormRec int
-- Добавление заголовка рецептуры
INSERT INTO dbo.tbNormRecCaption
	   (NumDoc, IdEnterprise, DateDoc, PNT, 
            NormVyhoda, IdEdRasch, Fasov) 
VALUES     (@NumDoc, @IdEnterprise, @DateDoc, @PNT, @NormVyhoda,
                   @IdEdRasch, @Fasov)
-- Определение нового идентификатора рецептуры
SET @IdNewNormRec = (SELECT @@IDENTITY)
-- Дублирование составляющих строк из старой рецептуры в новую
INSERT INTO dbo.tbNormRecString (IdNormRec, PNT, NormRash, IdPriznSyria )
SELECT @IdNewNormRec, PNT, NormRash, IdPriznSyria 
FROM dbo.tbNormRecString
WHERE IdNormRec = @IdNormRec
--
SELECT @IdNewNormRec AS IdNormRec

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[tchRecalcRashDS]
@IdFactRec int,
@PNT int,
@Rash float
--,
--@VyhodNew float = 0 OUTPUT
AS
/*
Процедура меняет расход в заданном основном сырье 
заданной производственной рецептуры и 
пересчитывает дополнительное сырье
*/
-- Определение cтарого расхода основного сырья
DECLARE @RashOldOS float
SET @RashOldOS = (SELECT SUM(Rash) FROM dbo.tbFactRecString WHERE IdFactRec = @IdFactRec AND IdPriznSyria = 1)
-- Изменение расхода основного сырья
UPDATE dbo.tbFactRecString
SET Rash = @Rash
WHERE PNT = @PNT AND IdFactRec = @IdFactRec
-- Определение нового расхода
DECLARE @RashNewOS float
SET @RashNewOS = (SELECT SUM(Rash) FROM dbo.tbFactRecString WHERE IdFactRec = @IdFactRec AND IdPriznSyria = 1)
-- Расчет для остального сырья
UPDATE dbo.tbFactRecString
SET Rash = CONVERT(DECIMAL(9,2),ROUND(@RashNewOS * Rash / @RashOldOS,2))
WHERE IdPriznSyria <> 1 AND IdPriznSyria <> 0 AND IdFactRec = @IdFactRec AND PriznakCalcWater = 1
/*
IF @VyhodNew = 0 -- Если выход не определен извне
BEGIN
-- Определение средневзвешенной влажности
DECLARE @VlajnSr float
SELECT @VlajnSr = dbo.GetVlajnSr(@IdFactRec)
-- Получение старого значения выхода
DECLARE @VyhodOld float
SELECT @VyhodOld = Vyhod FROM dbo.tbFactRecCaption WHERE IdFactRec = @IdFactRec
print 'vyhodold'
print @VyhodOld
-- Расчет скорректированной нормы выхода
SET @VyhodNew = @VyhodOld / ( @RashNewOS - ( 14.5 - @VlajnSr ) ) * 100
print 'rashnewos'
print @RashNewOS
print 'vyhodnew'
print @vyhodnew
END
-- Изменение значения выхода
UPDATE dbo.tbFactRecCaption
SET Vyhod = @VyhodNew
WHERE IdFactRec = @IdFactRec
*/

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.tchRecalcRashOS
@IdFactRec int,
@Vyhod float
AS
/*
Процедура меняет выход в производственной рецептуре, 
пересчитывает расход основного сырья, 
тем самым пересчитывает расход дополнительного сырья
*/
-- Получение старого выхода
DECLARE @VyhodOld float
SELECT @VyhodOld = Vyhod FROM dbo.tbFactRecCaption WHERE IdFactRec = @IdFactRec
-- Замена на новый выход
UPDATE dbo.tbFactRecCaption
SET Vyhod = @Vyhod
WHERE IdFactRec = @IdFactRec
DECLARE @PNT int
DECLARE @Rash float
DECLARE crsRecalcRashOS CURSOR
FOR 
	SELECT PNT, Rash
             FROM dbo.tbFactRecString
             WHERE IdFactRec = @IdFactRec AND IdPriznSyria = 1 -- только для основного сырья
OPEN crsRecalcRashOS
FETCH NEXT
FROM crsRecalcRashOS
INTO @PNT, @Rash
WHILE @@FETCH_STATUS = 0
BEGIN
	-- Определяем новое значение расхода
	SET @Rash = @Rash * @Vyhod / @VyhodOld
	-- Меняем расход основного сырья и пересчитываем дополнительное
	EXEC dbo.tchRecalcRashDS @IdFactRec, @PNT, @Rash--, @Vyhod
	FETCH NEXT
	FROM crsRecalcRashOS
	INTO @PNT, @Rash
END
CLOSE crsRecalcRashOS
DEALLOCATE crsRecalcRashOS

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[tchRecalcRashVyhod]
@IdFactRec int,
@PNT int,
@Data float,
@Vyhod  float = 0 OUTPUT
AS
/*
Процедура изменяет значение влажности для заданного вида 
основного сырья, пересчитывает выход, соответственно 
высчитывает новые значения расходов основного и дополнительного сырья
*/
-- Внесение новой влажности
UPDATE dbo.tbFactRecString
SET Data = @Data
WHERE IdFactRec = @IdFactRec AND PNT = @PNT
-- Расчет средневзвешенной влажности
DECLARE @VlajnSr float
DECLARE @Rash float
SELECT @Rash = SUM(Rash) 
FROM dbo.tbFactRecString 
WHERE IdFactRec = @IdFactRec AND IdPriznSyria = 1 -- только для основного сырья
IF @Rash > 0
	SELECT @VlajnSr = SUM(Rash * Data)/@Rash 
	FROM dbo.tbFactRecString 
	WHERE IdFactRec = @IdFactRec AND IdPriznSyria = 1 -- только для основного сырья
ELSE
	SET @VlajnSr = 0.0
-- Получение старой нормы выхода
DECLARE @VyhodOld float
SELECT @VyhodOld = Vyhod
FROM dbo.tbFactRecCaption
WHERE IdFactRec = @IdFactRec
-- Расчет значение нового выхода
DECLARE @VyhodNew float
SET @VyhodNew = @VyhodOld / ( @Rash - ( 14.5 - @VlajnSr ) ) * 100
-- Меняем значение выхода и соответственно остального
EXEC dbo.tchRecalcRashOS @IdFactRec, @VyhodNew
SET @Vyhod = @VyhodNew

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.tchSelectSyrieMy
@IdMetodOcenki int,
@KodSkl int,
--@IdEnterprise int,
@Groups varchar(5000)
AS
DECLARE @Cmd varchar(5000)
DECLARE @Skl varchar(500)
DECLARE @Enterprise varchar(500)
-- настройка на конкретный склад
IF @KodSkl  <> -1
 BEGIN
  IF @IdMetodOcenki = 1
  BEGIN
   SET @Skl = N'DECLARE @KodSkl int
   SET @KodSkl = ' + CAST(@KodSkl AS varchar(20)) + ' '
   SET @Cmd = @Skl + N' SELECT  st.PNT, st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, st.NameT,  st.NameTov , st.GlKod, 
              dbo.GetOstatok(1, @KodSkl, PNT, GETDATE() ) AS Ostatok,   dbo.GetCena(1, @KodSkl, PNT, GETDATE()) AS CenO,
              srt.NameSort, st.IdSort, se.EdIz, st.EdIzID,  st.PriznSyria, st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp,
              st.Fasov, st.Art, st.Vlajn, st.Jirn, st.IdPredpr, st.IdCountry , st.PNTTar1, st.PNTTar2, st.Ves, st.NDS,  st.IdPriznNac, IdEnterprise = 0
              FROM 
                   MainDatabase.dbo.SprTovar st 
                    LEFT OUTER JOIN MainDatabase.dbo.SprEdIz se ON se.EdIzID = st.EdIzID
                    LEFT OUTER JOIN MainDatabase.dbo.tbSort srt ON srt.IdSort = st.IdSort 
            where PNT in
                 (SELECT PNT from ( SELECT   max(s.PNT) as PNT, st.NameT, st.Vlajn, st.Jirn, srt.NameSort                     
                    FROM MainDatabase.dbo.DocString s
                    JOIN MainDatabase.dbo.DocCaption c ON c.IdDoc = s.IdDoc AND c.KodSkl = @KodSkl
                    JOIN MainDatabase.dbo.SprTovar st ON s.PNT = st.PNT 
                    LEFT OUTER JOIN MainDatabase.dbo.tbSort srt ON srt.IdSort = st.IdSort 
                   GROUP BY st.NameT, st.Vlajn, st.Jirn, srt.NameSort )as q)  ORDER BY NameT'-- ' + @Groups +N'
   END
   ELSE IF @IdMetodOcenki = 2
   BEGIN
   SET @Skl = N'DECLARE @KodSkl int
                        SET @KodSkl = ' + CAST(@KodSkl AS varchar(20)) + ' '
   SET @Cmd = @Skl + 
   N'  SELECT  DISTINCT st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, ds.PNT, st.NameT, st.NameTov,
                  st.GlKod,   dbo.GetOstatok(2, @KodSkl, ds.PNT, GETDATE()) AS Ostatok,
                  dbo.GetCena(2, @KodSkl, st.PNT, GETDATE()) AS CenO, srt.NameSort, st.IdSort, se.EdIz, st.EdIzID,  st.PriznSyria, 
                  st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, st.Vlajn, st.Jirn, st.IdPredpr, st.IdCountry ,
                  st.PNTTar1, st.PNTTar2, st.Ves, st.NDS, st.IdPriznNac
          FROM    MainDatabase.dbo.DocString ds
           INNER JOIN MainDatabase.dbo.DocCaption dc ON ds.IdDoc = dc.IdDoc AND dc.KodSkl = @KodSkl
           INNER JOIN MainDatabase.dbo.SprTovar st ON st.PNT = ds.PNT 
           LEFT OUTER JOIN MainDatabase.dbo.SprEdIz se ON se.EdIzID = st.EdIzID
           LEFT OUTER JOIN MainDatabase.dbo.tbSort srt ON srt.IdSort = st.IdSort ORDER BY st.NameT ' --+ @Groups + N' '
   END
  ELSE IF @IdMetodOcenki = 3
  BEGIN
  SET @Cmd = 
  N'SELECT PNT  AS PNT, st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, 0 as Ostatok, st.CenO, st.NameT, st.NameTov,
                  srt.NameSort, st.IdSort, se.EdIz, st.EdIzID,  st.PriznSyria, 
                  st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, st.Vlajn, st.Jirn, st.IdPredpr, st.IdCountry ,
                  st.PNTTar1, st.PNTTar2, st.Ves, st.NDS, st.IdPriznNac
  FROM       MainDatabase.dbo.SprTovar st 
                    LEFT OUTER JOIN MainDatabase.dbo.SprEdIz se ON se.EdIzID = st.EdIzID
                    LEFT OUTER JOIN MainDatabase.dbo.tbSort srt ON srt.IdSort = st.IdSort 
 where PNT in 
  (select PNT from ( SELECT   max(s.PNT) as PNT, st.NameT,st.Vlajn, st.Jirn,  srt.NameSort                     
                    FROM MainDatabase.dbo.DocString s
                    JOIN MainDatabase.dbo.SprTovar st ON s.PNT = st.PNT 
                    LEFT OUTER JOIN MainDatabase.dbo.tbSort srt ON srt.IdSort = st.IdSort 
                   GROUP BY st.NameT, st.Vlajn, st.Jirn, srt.NameSort ) as q)  ORDER BY NameT '-- + @Groups + N' '
END
END
-- для Справочника Сырья в Арм Кладовая
ELSE IF @KodSkl = -1
BEGIN
/*  SET @Enterprise = N' DECLARE @IdEnterprise int
       SET @IdEnterprise = '+ CAST(@IdEnterprise AS varchar(20)) + ' '*/
  SET @Cmd =/* @Enterprise + */
   N'  SELECT st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, st.PNT, st.NameT, st.NameTov , st.EdIzID, st.IdSort, st.PriznSyria, 
                       st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, st.Vlajn, st.Jirn, st.IdPredpr,st.IdCountry , 
                       st.PNTTar1, st.PNTTar2, st.Ves, st.CenO, st.NDS, se.EdIz, srt.NameSort,  st.IdPriznNac,  syr.IdEnterprise
          FROM MainDataBase.dbo.SprTovar st 
          LEFT OUTER JOIN  MainDataBase.dbo.SprEdIz se ON se.EdIzID = st.EdIzID
          LEFT OUTER JOIN  MainDataBase.dbo.tbSort srt ON srt.IdSort = st.IdSort
          INNER JOIN dbo.tbSyrie  syr ON syr.PNT = st.PNT   '+ @Groups  --  WHERE syr.IdEnterprise = @IdEnterprise  
 
 
END
print @Cmd
EXECUTE (@Cmd)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO


CREATE PROCEDURE dbo.temprRemainsRawMaterial 
@CODE_GR INT,
@CODE_SUBGR INT,
@CODE_ASSORTMENT INT,
@PNT_AS_KEY INT,
@NAME VARCHAR(100),
@AMOUNT DECIMAL (5,2),
@AVR_PRICE DECIMAL (5,2),
@UNIT CHAR(3)
AS
INSERT INTO ##RemainsSyrie VALUES( @CODE_GR,@CODE_SUBGR,@CODE_ASSORTMENT,
@PNT_AS_KEY,@NAME,@AMOUNT,@AVR_PRICE,@UNIT )


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


CREATE PROCEDURE dbo.updAccount
@NumOtchNew int,
@NumOtchOld int,
@DateOtch datetime,
@TabN int,
@KodSkl int
 AS
 update maindatabase.dbo.DocCaption
      set NumOtch = @NumOtchNew,
            DateOtch = @DateOtch,
            TabN = @TabN
 where (NumOtch = @NumOtchOld) and (KodSkl = @KodSkl)



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.updCostRawMaterial
@ID_DOC INT,
@COST_RAW_MATERIAL DECIMAL(10,2),
@COST_PACKAGE DECIMAL(10,2)
AS

BEGIN TRANSACTION
UPDATE maindatabase.dbo.doccaption SET itogo = @COST_RAW_MATERIAL + @COST_PACKAGE, itogotar = @COST_PACKAGE, itogotov = @COST_RAW_MATERIAL WHERE iddoc = @ID_DOC
IF @@ERROR <> 0
BEGIN
   ROLLBACK TRANSACTION
   RETURN	
END
COMMIT TRANSACTION
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.updDocCaption
@DateDoc datetime,
@NumDoc int,
@IdPredpr SMALLINT,
@IdGrOper SMALLINT,
--@Original_IdDoc int,
@IdDoc INT
AS
	
UPDATE maindatabase.dbo.DocCaption
 SET
  DateDoc = @DateDoc,
  NumDoc =  @NumDoc,
  IdPredpr = @IdPredpr,
  IdGrOper = @IdGrOper
 WHERE IdDoc = @IdDoc
           SELECT   dc.NumDoc, dc.DateDoc, dc.NumOtch, dc.DateOtch, pr.namePredprShort, 
                    dc.IdPredpr, dc.KodSkl, dc.VidDoc
            FROM  maindatabase.dbo.DocCaption dc INNER JOIN
                    maindatabase.dbo.tbPredpr pr ON dc.IdPredpr = pr.idPredpr
           WHERE dc.IdDoc = @IdDoc
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.updDocString
@CenAvg FLOAT,
@KolF FLOAT,
@CenO FLOAT = NULL,
@IdStr INT,
@KodSkl INT,
@PNT INT,
@NDS FLOAT,
@NalTr FLOAT,
@SkidPost FLOAT,
@NacPosr FLOAT,
@NacOpt FLOAT,
@SkidPokup FLOAT,
@NacObpit FLOAT,
@CenPriobr FLOAT,
@DateDoc DATETIME = NULL,
@CODE_WAREHOUSE INT = NULL,
@IdGrOper INT = -1
AS
--DECLARE @PNT INT
IF @NDS  IS NULL
 SET @NDS  = 0
IF @NalTr IS NULL
SET @NalTr  = 0
IF @SkidPost IS NULL
SET @SkidPost = 0
IF @NacPosr IS NULL
SET @NacPosr = 0
IF @NacOpt IS NULL
SET @NacOpt = 0
IF @SkidPokup IS NULL
SET @SkidPokup = 0
IF @NacObpit IS NULL
SET @NacObpit = 0
IF @CenPriobr IS NULL
SET @CenPriobr = 0
DECLARE  @ToDate DATETIME
SELECT @ToDate = dc.DateDoc 
--, @PNT = ds.PNT
FROM maindatabase.dbo.DocString ds
INNER JOIN maindatabase.dbo.DocCaption dc ON dc.IdDoc = ds.IdDoc
WHERE IdStr = @IdStr
DECLARE @NameVidSyrie VARCHAR(50)
SET @NameVidSyrie = (SELECT Rtrim(v.NameVid) + space(2) + IsNull(t.NameTov,'')
FROM maindatabase.dbo.SprTovar t INNER JOIN 
maindatabase.dbo.SprVid v ON t.KodGr = v.KodGr AND t.KodPGr = v.KodPGr AND t.KodVid = v.KodVid WHERE t.PNT = @PNT)
DECLARE @NAMET VARCHAR(90)
DECLARE @SORT CHAR(3)
DECLARE @VLAJN DECIMAL(5,2)
DECLARE @JIRN DECIMAL(5,2)
DECLARE @CODE_GR INT
DECLARE @CODE_SUBGR INT
DECLARE @CODE_ASSORT INT
DECLARE @CODE_RAZ1 INT
DECLARE @CODE_RAZ2 INT
DECLARE @ED_IZ INT
DECLARE @SORT_ID INT
DECLARE @NAMETOV VARCHAR(30)
SELECT  DISTINCT @CODE_GR = st.kodgr, @CODE_SUBGR =  st.kodpgr,@CODE_ASSORT =  st.kodvid,
@CODE_RAZ1 = st.KodR1,  @CODE_RAZ2 = st.KodR2,@ED_IZ =  st.edizid, 
@NAMET = st.namet, @VLAJN = COALESCE(st.vlajn,NULL), @JIRN = COALESCE(st.jirn,NULL), 
@SORT_ID = st.idsort,@NAMETOV = st.nametov,
@SORT = CASE COALESCE(st.idsort,0) WHEN 0 THEN NULL ELSE ts.namesort END 
FROM maindatabase.dbo.sprtovar st INNER JOIN maindatabase.dbo.tbsort ts 
ON  st.pnt = @PNT AND (st.idsort = ts.idsort OR st.idsort IS NULL)
IF (@SORT IS NULL)
  SET @SORT = ''
IF (@VLAJN IS NULL)
  SET @VLAJN = 0
IF (@JIRN IS NULL)
  SET @JIRN = 0
DECLARE @PNT_AS_KEY INT
SELECT @PNT_AS_KEY = ISNULL(MIN(ID),0) FROM Technolog.dbo.tbGoods 
WHERE code_gr = @CODE_GR AND code_subgr = @CODE_SUBGR AND code_assort = @CODE_ASSORT AND code_raz1 = @CODE_RAZ1 
AND code_raz2 = @CODE_RAZ2 AND nametov = @NAMETOV AND sort = @SORT AND vlajn = COALESCE(@VLAJN,0) AND jirn = COALESCE(@JIRN,0)

DECLARE @CODE_REMAINS INT
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT

BEGIN TRANSACTION
IF @PNT_AS_KEY = 0
BEGIN
    INSERT INTO Technolog.dbo.tbGoods  (code_gr,code_subgr,code_assort,code_raz1,code_raz2,namet,sort,vlajn,jirn,idsort,edizid,nametov) 
    VALUES (@CODE_GR,@CODE_SUBGR,@CODE_ASSORT,@CODE_RAZ1,@CODE_RAZ2,@NAMET,@SORT,@VLAJN,@JIRN,@SORT_ID,@ED_IZ,@NAMETOV)
    IF @@ERROR <> 0
    BEGIN
       ROLLBACK TRANSACTION
       RETURN		
    END
    SET @PNT_AS_KEY = @@IDENTITY
    IF @IdGrOper =  @CODE_REMAINS
    BEGIN
	EXEC dbo.saveRemainsAvrPrice @PNT_AS_KEY, @CenAvg, @KOLF,@DATEDOC,@CODE_WAREHOUSE
             IF @@ERROR <> 0
             BEGIN
                ROLLBACK TRANSACTION
             RETURN
    END
    END
END
ELSE
BEGIN
    IF @idGrOper = @CODE_REMAINS 
    BEGIN       
     -- SET @REM = ABS(@KOLF-@REM)
      EXEC dbo.saveRemainsAvrPrice @PNT_AS_KEY, @CenO, @KOLF ,@DATEDOC,@CODE_WAREHOUSE
      IF @@ERROR <> 0
      BEGIN
                ROLLBACK TRANSACTION
                RETURN
            END
    END
END

UPDATE maindatabase.dbo.DocString
SET namevidtov = @NameVidSyrie,KolF = @KolF, pnt = @PNT, pnt_as_key =  @PNT_AS_KEY,
nds = @NDS,naltr = @NalTr,skidpost = @SkidPost, nacposr = @NacPosr ,nacopt = @NacOpt,

skidpokup = @SkidPokup, nacobpit = @NacObpit,cenpriobr = @CenPriobr
WHERE IdStr = @IdStr
IF @@ERROR <> 0
BEGIN
      ROLLBACK TRANSACTION		
      RETURN
END
COMMIT TRANSACTION
SELECT ds.IdStr, ds.PNT, dbo.GetNameSyrie(ds.PNT) AS NameSyrie,
	           ds.CenO, ds.CenRoz, e.EdIz, ds.IdDoc, t.Sertif, t.KodGr,ds.nds,ds.naltr,ds.skidpost,
	           ds.nacposr,ds.nacobpit,ds.skidpokup,ds.nacopt,ISNULL(ds.cenpriobr,0) AS cenpriobr, ds.pnt_as_key
FROM         maindatabase.dbo.DocString ds INNER JOIN
                      maindatabase.dbo.SprTovar t ON t.PNT = ds.PNT LEFT OUTER JOIN
                      maindatabase.dbo.SprEdIz e ON e.EdIzID = t.EdIzID 
WHERE   (ds.IdStr = @IdStr)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.updFactRecCaption 
@DateDoc datetime,
@Original_IdFactRec int,
@IdFactRec int
AS
UPDATE    dbo.tbFactRecCaption
SET              DateDoc = @DateDoc
WHERE     (IdFactRec = @Original_IdFactRec);
                          SELECT     fc.Vyhod, fc.IdFactRec, fc.IdNormRec, nc.NumDoc, fc.DateDoc, nc.PNT, dbo.GetTovName(nc.PNT) AS NameTov, e.EdIz, nc.Fasov,
                                        nc.NormVyhoda
                           FROM         dbo.tbFactRecCaption fc INNER JOIN
                                                  dbo.tbNormRecCaption nc ON fc.IdNormRec = nc.IdNormRec INNER JOIN
                                                  MainDataBase.dbo.SprTovar t ON t .PNT = nc.PNT LEFT OUTER JOIN
                                                  MainDataBase.dbo.SprEdIz e ON e.EdIzID = t .EdIzID
                           WHERE     (IdFactRec = @IdFactRec)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[updFactRecString]
@PNT int,
@PriznakCalcWater bit, 
@Original_IdFactStr int,
@IdFactStr int
AS
UPDATE    dbo.tbFactRecString
SET              PNT = @PNT, PriznakCalcWater = @PriznakCalcWater
WHERE     (IdFactStr = @Original_IdFactStr);
                          SELECT     fs.IdFactStr, fs.IdFactRec, fs.PNT, dbo.GetTovName(fs.PNT) AS NameTov, fs.Rash, fs.IdPriznSyria, e.EdIz, ps.NamePriznSyria, 
                                                  fs.PriznakCalcWater
                           FROM         dbo.tbFactRecString fs INNER JOIN
                                                  MainDataBase.dbo.SprTovar t ON t .PNT = fs.PNT INNER JOIN
                                                  MainDataBase.dbo.SprPriznSyria ps ON ps.IDPriznSyria = fs.IdPriznSyria LEFT OUTER JOIN
                                                  MainDataBase.dbo.SprEdIz e ON e.EdIzID = t .EdIzID
                           WHERE     (IdFactStr = @IdFactStr)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.updMol
@TABN INT,
@PROF SMALLINT,
@FIO VARCHAR(45),
@MAT_OTV BIT
AS
UPDATE maindatabase.dbo.spr_works 
SET profes = @PROF,fio =@FIO,mat_otv =  @MAT_OTV WHERE tabn = @TABN
SELECT sw.tabn,sw.fio,sw.profes AS profes,sw.kodmol,sw.mat_otv FROM maindatabase.dbo.spr_works sw WHERE tabn = @TABN
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

CREATE PROCEDURE dbo.updPriznSyria
(
	@NamePriznSyria varchar(30),
	@Original_IDPriznSyria smallint
)
AS
	SET NOCOUNT OFF;
UPDATE MainDataBase.dbo.SprPriznSyria SET NamePriznSyria = @NamePriznSyria WHERE (IDPriznSyria = @Original_IDPriznSyria)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.updProduction
  @KodGr tinyint,
  @KodPGr tinyint, 
  @KodVid tinyint, 
  @KodR1 tinyint, 
  @KodR2 tinyint, 
  @CenO decimal(18,3),
  @NameTov varchar(30), 
  @IdSort tinyint,
  @EdIzID smallint, 
  @PriznSyria varchar(50),
  @DatePrih datetime,
  @SrokGodn varchar(16),
  @Sertif  varchar(255), 
  @VidUp char(5),
  @MinUp decimal(7,3), 
  @Fasov decimal(7,3), 
  @Art  varchar(30), 
  @Vlajn decimal(5,2),
  @Jirn decimal(5,2),
  @IdPredpr int,
  @IdCountry smallint,
  @PNTTar1 int,
  @PNTTar2 int,
  @Ves decimal(7,2),
  @NDS decimal(5,2), 
  @IdPriznNac tinyint, 
  @IdEnterprise int,
  @PrSyrja TINYINT,	 
  @PNT INT	
 AS

DECLARE @CODE_GR INT
DECLARE @CODE_SUBGR INT
DECLARE @CODE_ASSORT INT
DECLARE @NAME_ASSORT VARCHAR(20)
DECLARE @NAME_RAZ1 VARCHAR(20)
DECLARE @NAME_RAZ2 VARCHAR(20)

SELECT @CODE_GR = kodgr, @CODE_SUBGR = kodpgr, @CODE_ASSORT = kodvid 
FROM maindatabase.dbo.sprtovar WHERE pnt = @PNT
SELECT @NAME_RAZ1 = RTRIM(LTRIM(namer1)) FROM maindatabase.dbo.sprraz1 
WHERE kodgr = @CODE_GR AND kodpgr = @CODE_SUBGR AND kodr1 = @KodR1
SELECT @NAME_RAZ2 = RTRIM(LTRIM(namer2)) FROM maindatabase.dbo.sprraz2 
WHERE kodgr = @CODE_GR AND kodpgr = @CODE_SUBGR AND kodr2 = @KodR2
SELECT @NAME_ASSORT = RTRIM(LTRIM(namevid)) FROM maindatabase.dbo.sprvid
WHERE kodgr = @CODE_GR AND kodpgr = @CODE_SUBGR AND kodvid = @CODE_ASSORT

IF @NAME_RAZ1 IS NULL
BEGIN
   SET @NAME_RAZ1 = ''
END

IF @NAME_RAZ2 IS NULL
BEGIN
   SET @NAME_RAZ2 = ''
END

IF @NAME_ASSORT IS NULL
BEGIN
   SET @NAME_ASSORT = ''
END

UPDATE    MainDatabase.dbo.SprTovar
SET KodGr = @KodGr, KodPGr = @KodPGr, KodVid = @KodVid, KodR1 = @KodR1, 
KodR2 =  @KodR2, CenO = @CenO, NameTov = @NameTov, 
IdSort =  @IdSort, EdIzID = @EdIzID, DatePrih = @DatePrih, SrokGodn = @SrokGodn, 
Sertif = @Sertif, VidUp = @VidUp, MinUp = @MinUp, Fasov = @Fasov, Art = @Art, Vlajn = @Vlajn, 
Jirn = @Jirn,   IdPredpr = @IdPredpr, IdCountry = @IdCountry, PNTTar1 = @PNTTar1, PNTTar2 = 
                     @PNTTar2, Ves = @Ves, NDS = @NDS, IdPriznNac = @IdPriznNac, 
	        NameT = RTRIM(@NAME_ASSORT) + ' ' + RTRIM(@NAME_RAZ1) + ' ' + RTRIM(@NAME_RAZ2) + ' '  + RTRIM(@NameTov), PrSyrja = @PrSyrja
WHERE     (PNT = @PNT);
                          SELECT     st.PNT, st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, 0 AS Ostatok, st.CenO, st.NameT, st.NameTov, ss.NameSort, st.IdSort, 
                                                  ei.EdIz, st.EdIzID, st.PriznSyria, st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, st.Vlajn, st.Jirn, st.IdPredpr, 
                                                  st.IdCountry, st.PNTTar1, st.PNTTar2, st.Ves, st.NDS, st.IdPriznNac, st.PrSyrja, p.IdEnterprise, pn.NamePriznNac
                           FROM         MainDatabase.dbo.SprTovar st LEFT OUTER JOIN
                                                  MainDatabase.dbo.tbPriznNac pn ON st.IdPriznNac = pn.IdPriznNac LEFT OUTER JOIN
                                                  MainDatabase.dbo.SprEdIz ei ON ei.EdIzID = st.EdIzID LEFT OUTER JOIN
                                                  MainDatabase.dbo.tbSort ss ON ss.IdSort = st.IdSort INNER JOIN
                                                  tbProd p ON st.PNT = p.PNT
                           WHERE     (IdEnterprise = @IdEnterprise) AND (p.PNT = @PNT)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[updSyrie]
 @KodR1 tinyint, 
 @KodR2 tinyint,
 @NameTov varchar(30), 
 @EdIzID smallint, 
 @IdSort tinyint,
 @PrSyrja tinyint,
-- @PriznSyria varchar(50),
 @DatePrih datetime,
 @SrokGodn varchar(10),
 @Sertif  varchar(255), 
 @VidUp char(5),
 @MinUp decimal(7,3), 
 @Fasov decimal(7,3), 
 @Art  varchar(30), 
 @Vlajn decimal(5,2),
 @Jirn decimal(5,2),
 @IdPredpr int,
 @IdCountry smallint,
 @PNTTar1 int,
 @PNTTar2 int,
 @Ves decimal(7,2),
 @NDS decimal(5,2), 
 @IdPriznNac tinyint, 
 @PNT int,
 @IdEnterprise int,
 @NalTr DECIMAL(18,3) = NULL,
 @SkidPost DECIMAL(18,3) = NULL,
 @NacPosr DECIMAL(18,3) = NULL,
 @CenPriobr DECIMAL(18,3) = NULL
 
AS
DECLARE @CODE_GR INT
DECLARE @CODE_SUBGR INT
DECLARE @CODE_ASSORT INT
DECLARE @NAME_ASSORT VARCHAR(20)
DECLARE @NAME_RAZ1 VARCHAR(20)
DECLARE @NAME_RAZ2 VARCHAR(20)
SELECT @CODE_GR = kodgr, @CODE_SUBGR = kodpgr, @CODE_ASSORT = kodvid 
FROM maindatabase.dbo.sprtovar WHERE pnt = @PNT
SELECT @NAME_RAZ1 = RTRIM(LTRIM(namer1)) FROM maindatabase.dbo.sprraz1 
WHERE kodgr = @CODE_GR AND kodpgr = @CODE_SUBGR AND kodr1 = @KodR1
SELECT @NAME_RAZ2 = RTRIM(LTRIM(namer2)) FROM maindatabase.dbo.sprraz2 
WHERE kodgr = @CODE_GR AND kodpgr = @CODE_SUBGR AND kodr2 = @KodR2
SELECT @NAME_ASSORT = RTRIM(LTRIM(namevid)) FROM maindatabase.dbo.sprvid
WHERE kodgr = @CODE_GR AND kodpgr = @CODE_SUBGR AND kodvid = @CODE_ASSORT
IF @NAME_RAZ1 IS NULL
BEGIN
   SET @NAME_RAZ1 = ''
END
IF @NAME_RAZ2 IS NULL
BEGIN
   SET @NAME_RAZ2 = ''
END
IF @NAME_ASSORT IS NULL
BEGIN
   SET @NAME_ASSORT = ''
END
UPDATE  MainDataBase.dbo.SprTovar
SET        KodR1 =  @KodR1, 
               KodR2 =  @KodR2 , 
	  NameT = @NAME_ASSORT + '  ' + @NAME_RAZ1 + '  ' + @NAME_RAZ2 +  '  ' + @NameTov,
               NameTov = @NameTov, 
               EdIzID =  @EdIzID, 
               IdSort = @IdSort,
               --PriznSyria = @PriznSyria,
	  PrSyrja = @PrSyrja,
               DatePrih = @DatePrih,
               SrokGodn = @SrokGodn,
               Sertif  =  @Sertif , 
               VidUp = @VidUp,
               MinUp =  @MinUp, 
               Fasov = @Fasov , 
               Art = @Art , 
               Vlajn = @Vlajn,
               Jirn = @Jirn,
               IdPredpr = @IdPredpr,
               IdCountry =  @IdCountry,
               PNTTar1 = @PNTTar1,
               PNTTar2  = @PNTTar2 ,
               Ves = @Ves,
               NDS =  @NDS, 
               IdPriznNac =  @IdPriznNac,
               naltr =  @NalTr,
	 skidpost = @SkidPost,
              nacposr = @NacPosr 
WHERE     (PNT = @PNT);
SELECT  st.KodGr, st.KodPGr, st.KodVid, st.KodR1, st.KodR2, st.PNT, st.NameT, st.NameTov ,st.EdIzID,st.IdSort, st.PrSyrja, 
                st.DatePrih, st.SrokGodn, st.Sertif, st.VidUp, st.MinUp, st.Fasov, st.Art, st.Vlajn, st.Jirn, st.IdPredpr,st.IdCountry , 
                st.PNTTar1, st.PNTTar2, st.Ves, st.CenO,st.NDS, e.EdIz, s.NameSort,  syr.IdEnterprise
 FROM         MainDataBase.dbo.SprTovar st LEFT OUTER JOIN
                    MainDataBase.dbo.tbSort s ON s.IdSort = st.IdSort LEFT OUTER JOIN
                    MainDataBase.dbo.SprEdIz e ON e.EdIzID = st.EdIzID INNER JOIN
                    dbo.tbSyrie syr ON syr.PNT = st.PNT
 WHERE     (syr.IdEnterprise = @IdEnterprise) and (syr.PNT = @PNT)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.updateWeightedAveragePriceForAccounting
@PNT_AS_KEY INT,
@CODE_WAREHOUSE INT,
@PRICE DECIMAL(8,2),
@START_DATE DATETIME,
@END_DATE DATETIME
AS
SET NOCOUNT ON
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
UPDATE maindatabase.dbo.docstring SET ceno = @PRICE FROM maindatabase.dbo.doccaption dc, maindatabase.dbo.docstring ds
WHERE dc.iddoc = ds.iddoc
AND dc.idgroper NOT IN (@CODE_ARRIVED_OUT, @CODE_LEFT_OUT,@CODE_REMAINS) AND dc.datedoc >= @START_DATE AND dc.datedoc <= @END_DATE
AND ds.pnt_as_key = @PNT_AS_KEY AND dc.kodskl = @CODE_WAREHOUSE
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE writeTotalsMovingRawMaterialByName 
@CODE_WAREHOUSE INT,
@PNT INT,
@END_DATE DATETIME,
@ARRIVED_AMOUNT DECIMAL(10,2) =0,
@ARRIVED_SUM DECIMAL(10,2) =0,
@LEFT_AMOUNT DECIMAL(10,2) =0,
@LEFT_SUM DECIMAL(10,2) =0
AS
SET NOCOUNT ON
UPDATE technolog.dbo.tbgoodsremains SET arrived_amount = @ARRIVED_AMOUNT, arrived_sum = @ARRIVED_SUM, left_amount = @LEFT_AMOUNT, left_sum = @LEFT_SUM
WHERE pnt_as_key = @PNT AND code_warehouse = @CODE_WAREHOUSE AND accountdategoods = @END_DATE


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.writeWeightedAveragePrice 
@PNT_AS_KEY INT,
@PRISE DECIMAL(8,2),
@REMAINS DECIMAL(8,2),
@IDSTR INT,
@ENDDATE DATETIME,
@CODE_WAREHOUSE INT,
@CLOSE_MONTH BIT = 0
AS
SET NOCOUNT ON
--START
DECLARE @CODE_ARRIVED_OUT INT
DECLARE @CODE_LEFT_OUT INT
DECLARE @CODE_ARRIVED_IN INT
DECLARE @CODE_LEFT_IN INT
DECLARE @CODE_REMAINS INT
EXECUTE dbo.getCodes @CODE_ARRIVED_OUT = @CODE_ARRIVED_OUT OUTPUT, @CODE_LEFT_OUT = @CODE_LEFT_OUT OUTPUT,
@CODE_ARRIVED_IN = @CODE_ARRIVED_IN OUTPUT, @CODE_LEFT_IN =  @CODE_LEFT_IN OUTPUT, @CODE_REMAINS = @CODE_REMAINS OUTPUT
--END
--Write a resulting weighted average price  into dostring->cen0 field for all inside operatons
--DECLARE @START_DATE_MONTH DATETIME
--SET  @START_DATE_MONTH =  CONVERT(CHAR(8),@ENDDATE,120)+'01'
--SELECT CONVERT(CHAR(10),DATEADD(day,-1,DATEADD(month,1,CONVERT(CHAR(8),CURRENT_TIMESTAMP,120)+'01')),120) 
BEGIN TRANSACTION
--UPDATE maindatabase.dbo.docstring SET ceno = @PRISE FROM maindatabase.dbo.doccaption dc, maindatabase.dbo.docstring ds
--WHERE dc.iddoc = ds.iddoc AND dc.idgroper IN (@CODE_ARRIVED_IN, @CODE_LEFT_IN) AND dc.datedoc >= @START_DATE_MONTH AND dc.datedoc <= @ENDDATE
--AND ds.pnt_as_key = @PNT_AS_KEY AND dc.kodskl = @CODE_WAREHOUSE
IF @@ERROR <> 0
BEGIN
  ROLLBACK TRANSACTION
  RETURN
END
IF EXISTS(SELECT pnt_as_key FROM technolog.dbo.tbgoodsremains WHERE pnt_as_key = @PNT_AS_KEY AND code_warehouse = @CODE_WAREHOUSE
AND accountDateGoods = @ENDDATE)
BEGIN
     UPDATE  technolog.dbo.tbgoodsremains SET remains = @REMAINS, avr_price = @PRISE,status = @CLOSE_MONTH 
     WHERE pnt_as_key = @PNT_AS_KEY AND accountDateGoods = @ENDDATE AND code_warehouse = @CODE_WAREHOUSE
END
ELSE
BEGIN
     INSERT INTO technolog.dbo.tbgoodsremains(pnt_as_key,accountdategoods,code_warehouse,remains,avr_price,status) VALUES (@PNT_AS_KEY, @ENDDATE,@CODE_WAREHOUSE,@REMAINS,@PRISE,@CLOSE_MONTH)
END
IF @@ERROR <> 0
BEGIN
  ROLLBACK TRANSACTION
  RETURN
END
COMMIT TRANSACTION
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

