--fiesGO
--BUILD Ver 0.0
--Date of creation: 06.03.2012
--Purpose : To track database structure changes.
--Procedure: QA team will track the database structural changes and those changes 
--will be appended in sql in the form of Build versions.

--LEGENDS
--TABLE		: FINDTABLE
--TRIGGER	: FINDTRIGGER
--SP		: FINDSP
--VIEW		: FINDVIEW
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--FINDTABLE
--TABLE CREATIONS AND ALTERATIONS

--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

USE adminv2

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_028
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
DECLARE @ReportID INT
SET @ReportID = 0
SELECT @ReportID = ReportID 
FROM AREPORTS 
WHERE ReportID = 7190
IF @ReportID = 0
	BEGIN
		INSERT INTO AREPORTS VALUES(7190,'Unposted Shop Transactions','UnpostedShopTrans',4,9,'acc',1)
	END

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_030
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
update losLocalPurchaseHeader set lphConfirmed=1  where lphPosted=1
Go
update losLocalPurchaseHeader set lphConfirmed=1  where lphcosted=1

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_109
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


		insert into atablecolumns values (69,8,'lpchCostingDone','Costing Done','Costing Done','bit',0,0,1,1,NEWID())

	
	
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_116
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


/****** Object:  Table [dbo].[aRateEditingDetails]    Script Date: 04/04/2012 12:25:05 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[aRateEditingDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[aRateEditingDetails](
	[redID] [int] NOT NULL,
	[redDate] [datetime] NOT NULL,
	[reditemid] [int] NOT NULL,
	[reduserid] [int] NOT NULL,
	[redcompanyid] [int] NOT NULL,
	[redoldcostprice] [numeric](18, 8) NOT NULL,
	[redcostprice] [numeric](18, 8) NOT NULL,
	[UpdateDateTime] [datetime] NOT NULL,
 CONSTRAINT [PK_aRateEditingDetails] PRIMARY KEY CLUSTERED 
(
	[redID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_052
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--GO
use [adminv2]
GO


/****** Object:  Table [dbo].[aHpProcessingDetailOthers]    Script Date: 11/04/2011 17:08:31 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[aHpProcessingDetailOthers]') AND type in (N'U'))
BEGIN
                
CREATE TABLE [dbo].[aHpProcessingDetailOthers](
	[hpdCompanyID] [int] NOT NULL,
	[hpdDepartmentID] [int] NOT NULL,
	[hpdProcessingId] [int] NOT NULL,
	[hpddetailIDBT] [int] NOT NULL,
	[hpdChequeDateBT] [datetime] NOT NULL,
	[hpdCapitalBT] [numeric](18, 2) NOT NULL,
	[hpdRentalBT] [numeric](18, 2) NOT NULL,
	[hpdInterestBT] [numeric](18, 2) NOT NULL,
	[hpdcapitalRepaymentBT] [numeric](18, 2) NOT NULL,
	[hpdCapitalBalanceBT] [numeric](18, 2) NOT NULL,
	[hpdBankNameBT] [nvarchar](50) NULL,
	[hpdChequeNoBT] [nvarchar](50) NULL,
	[hpdAmountBT] [numeric](18, 2) NULL,
	[hpdSettlementAmountBT] [numeric](18, 2) NULL,
	[hpdInterestRateBT] [numeric](18, 2) NULL,
	[hpdPosted] [int] NULL,
	[hpdChequeStatus] [varchar](50) NULL,
PRIMARY KEY CLUSTERED 
(
	[hpdCompanyID] ASC,
	[hpdDepartmentID] ASC,
	[hpdProcessingId] ASC,
	[hpddetailIDBT] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
end
GO

SET ANSI_PADDING OFF

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_083
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


DECLARE @InterfaceID INT
SET @InterfaceID = 0
SELECT @InterfaceID = InterfaceID 
FROM aInterface 
WHERE InterfaceID = 8030
IF @InterfaceID = 0
	BEGIN
		insert into aInterface (InterfaceID,InterfaceName,ModuleCode,PrefixNeeded,CompanyID,menuname,rowguid,customize)
       values (8030,'Local Purchase Confirmation','P&C',0,1,NULL,newid(),NULL)
	END
	

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='LOsInvoiceDetail' AND COLUMN_NAME='idBillID' ) 
BEGIN
ALTER TABLE [dbo].[LOsInvoiceDetail] ADD [idBillID] [numeric](18, 0) NULL
END
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_178
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
DECLARE @ReportID INT
SET @ReportID = 0
SELECT @ReportID = ReportID 
FROM AREPORTS 
WHERE ReportID = 7192
IF @ReportID = 0
	BEGIN
		insert into aReports values (7192,'CreditInvoice-BillWise','cuscrbil',3,1,'poscbRRR',1) 
	END

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:MD_034
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='lospPurchaseBilldetail' AND COLUMN_NAME='pbdDummyUnitPrice' ) 
BEGIN
alter table lospPurchaseBilldetail alter column pbdDummyUnitPrice NUMERIC(28,13)
END
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
DECLARE @InterfaceID INT
SET @InterfaceID = 0
SELECT @InterfaceID = InterfaceID 
FROM aInterface 
WHERE InterfaceID = 1905
IF @InterfaceID = 0
	BEGIN
	 insert into aInterface values (1905,'TotalStock Verification','poscbR',1,1,NULL,NEWID(),NULL)
	END
GO
DECLARE @InterfaceID INT
SET @InterfaceID = 0
SELECT @InterfaceID = InterfaceID 
FROM aInterface 
WHERE InterfaceID = 7521
IF @InterfaceID = 0
	BEGIN
insert into aInterface values (7521,'HP Default Charge','poscbR',0,1,NULL,NEWID(),NULL)
	END
GO
DECLARE @InterfaceID INT
SET @InterfaceID = 0
SELECT @InterfaceID = InterfaceID 
FROM aInterface 
WHERE InterfaceID = 92033
IF @InterfaceID = 0
	BEGIN
insert into aInterface values (92033,'Accounts Tool','acc',0,1,NULL,NEWID(),NULL)
	END
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

INSERT INTO atablecolumns VALUES(78,11,'serinvposted','posted','posted','numeric',15,0,1,1,newid())
	
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_047, M_189, M_237
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='aSettings' AND COLUMN_NAME='GainOrLossOnAssetDisposal' ) 
BEGIN
ALTER TABLE aSettings ADD GainOrLossOnAssetDisposal INTEGER
END
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

insert into atablecolumns values
(41,9,'phConfirmed','Confirmed','Confirmed','bit',1,NULL,1,1,newid())

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
alter table aTaxCategoryMaster alter column TaxAccountId int null
alter table aTaxCategoryMaster alter column TaxInputAccountId int null
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

insert into aTableColumns values(60,9,'Confirmed','Confirmed','Confirmed','bit',1,NULL,1,1,newid())
insert into aTableColumns values(53,8,'DCNConfirmed','Confirmed','Confirmed','bit',1,NULL,1,1,newid())
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

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

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--FINDTRIGGER
--TRIGGER CREATIONS AND ALTERATIONS

--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_177
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO
/****** Object:  Trigger [dbo].[TRIGGER_UPDATE_ITEMPRICEHISTORY]    Script Date: 04/21/2012 11:26:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		VinothMurugan V.
-- Create date: 07/08/2010
-- Description:	Update Item Price History When losShopitemShipmentDetail is Updated.
--------------------------------------------------
-- Ref 01    
-- Modified By : Benzigar S D
-- Modified on : 21/04/2012
-- Description : If losShopitemShipmentDetail is blank error occurs. Corrected this
-- =============================================


if exists (
    select * from dbo.sysobjects 
    where name = 'TRIGGER_UPDATE_ITEMPRICEHISTORY' 
    and OBJECTPROPERTY(id, 'IsTrigger') = 1
) 
begin
drop trigger TRIGGER_UPDATE_ITEMPRICEHISTORY
end

GO

CREATE TRIGGER [dbo].[TRIGGER_UPDATE_ITEMPRICEHISTORY] ON [dbo].[losShopItemShipmentDetail] 
   AFTER  
   INSERT,
   DELETE,
   UPDATE
AS 
BEGIN
	
	SET NOCOUNT ON;
   
	DECLARE @ItemId AS INT,
			@PackId AS INT,
			@ShopId AS INT,
			@SegmentId AS INT,
			@CurrencyId AS INT,
			@SellingPrice AS NUMERIC(18,2),
			@DiscountPrice AS  NUMERIC(18,2),
			@WholesalePrice AS NUMERIC(18,2),
			@CreditSP AS NUMERIC(18,2),
			@CreditDP AS NUMERIC(18,2),
			@CreditWP AS NUMERIC(18,2),
			@FixDate AS DATETIME,
			@UpdateTime AS DATETIME,
			@UserId AS NUMERIC(18,2),
			@CompanyId AS NUMERIC(18,2),
			@FinancialId AS NUMERIC(18,2),
			@rowguid AS NUMERIC(18,2)

	SET @UpdateTime = (SELECT GETDATE())

	SELECT @ItemId = itemid,
			@PackId = PackingTypeid,
			@ShopId = shopid,
			@SegmentId = segmentid,
			@CurrencyId = currencyid,
			@SellingPrice = sellingPrice,
			@DiscountPrice = DiscountPrice,
			@WholesalePrice = WholesalePrice,
			@CreditSP = CreditSP,
			@CreditDP = CreditDP,
			@CreditWP = CreditWP,
			@FixDate = spFixdate,			
			@UserId = Userid,
			@CompanyId = companyid 

	FROM   losShopitemShipmentDetail

if (select COUNT(*) from losshopitemshipmentdetail)>=1 
begin
INSERT INTO ItemPriceHistory(ItemId,PackId,	ShopId,SegmentId,CurrencyId,SellingPrice,DiscountPrice,
							 WholesalePrice,CreditSP,CreditDP,CreditWP,FixDate,UpdateTime,UserId,CompanyId) 
		VALUES(@ItemId ,@PackId,@ShopId,@SegmentId ,@CurrencyId ,@SellingPrice ,@DiscountPrice ,
			@WholesalePrice ,@CreditSP ,@CreditDP ,	@CreditWP,@FixDate,@UpdateTime,	@UserId ,@CompanyId )
  
end
END

GO

 GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
update miscInquiry set query='SpServiceAlerts ?C?,?S?,'''',''''' where  queryid = 7056
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_177
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--FINDVIEW
--VIEW CREATIONS AND ALTERATIONS

--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************

--Added to build on : 14/03/2012
Go
-- Created by : Hariharan     
-- Created on : 19/01/2004 (at Male' From V2)    
-- Comments   : For alert display of unconfirmed transactions    
-- =================================================================       
-- Ref.No:1
-- Upgraded By : AADYAKUMAR D V      
-- Upgraded On : 13-03-2012        
-- Upgrade     : Added more transactions     
-- ==================================================================       
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwUnConfirmedTransactions]'))
BEGIN
	DROP VIEW vwUnConfirmedTransactions
END
GO   
    
Create VIEW dbo.vwUnConfirmedTransactions AS    
    
SELECT 'Despatch Note Generation' TransactionType, dnmDespatchNoteId TransactionId,    
dnmDespatchNoteNo TransactionNo, dnmDespatchNoteDate TransactionDate,     
0 LocationId, 'HQ' LocationName, Departmentid, 'H' LocType    
FROM aHqDespatchNoteMain Main LEFT OUTER JOIN aHqDespatchNoteHeader Header    
ON Main.dnmDespatchNoteId = Header.dhDespatchNoteMainID    
WHERE dnmCancelled = 0 AND dhTransFinished = 0 group by     
dnmDespatchNoteId, dnmDespatchNoteNo, dnmDespatchNoteDate, Departmentid    
    
    
UNION ALL    
    
SELECT 'Issue Note Generation' TransactionType, inmIssueNoteId TransactionId,    
inmIssueNoteNo TransactionNo, inmIssueDate TransactionDate,     
0 LocationId, 'HQ' LocationName, Departmentid, 'H' LocType    
FROM aHqIssueNoteMain Main LEFT OUTER JOIN aHqIssueNoteHeader Header    
ON Main.inmIssueNoteId = Header.inhIssueNoteMainId    
    
WHERE inmCancel = 0    
AND inhTransFinished = 0 group by inmIssueNoteId ,    
inmIssueNoteNo, inmIssueDate, Departmentid    
    
UNION ALL    
    
    
SELECT 'Costing', chCostingId, chCostingNo, chCostingDate, 0, 'HQ', chDepartmentId, 'H' LocType    
FROM loaCostingHeader WHERE chCancelled = 0 AND chCostingDone = 0    
and chCostingId >0    
    
UNION ALL    
    
SELECT 'Local Purchase Costing', lpchCostingId, lpchCostingNo, lpchDate, 0, 'HQ',     
lpchDepartmentid, 'H' LocType FROM loaLocalPurchaseCostingHeader    
WHERE lpchCancelled = 0    
AND lpchCostingDone = 0    
    
UNION ALL    
    
SELECT 'Item Split Costing', scfhId, scfhNo, scfhDate, 0, 'HQ', scfhdepartmentid, 'H' LocType    
FROM loaItemSplitCostingHeader    
WHERE scfhCancelled = 0    
AND scfhCostFixed = 0    
    
UNION ALL    
    
SELECT 'Goods Arrival To Godown', ahArrivalId, ahArrivalNo, ahArrivalDate,     
ahLocalGodownId, aGodown.GodownName, ahDepartmentid, 'G' LocType    
FROM loiArrivalHeader LEFT OUTER JOIN aGodown    
ON ahLocalGodownId = GodownId    
WHERE ahCancelled = 0    
AND ahTransFinished = 0    
    
UNION ALL    
    
    
SELECT 'Despatch To Shop', dhDespatchId, dhDespatchNo, dhDespatchDate,     
dhGodownId, GodownName, dhDepartmentId, 'g' LocType    
FROM meiDespatchToShopHeader LEFT OUTER JOIN aGodown    
ON dhGodownId = GodownId    
WHERE dhCancelled = 0    
AND dhTransFinished = 0    
    
UNION ALL    
    
SELECT 'Godown To Godown Transfer', gthDespatchId, gthDespatchNo, gthDespatchDate,     
gthFromGodownId, GodownName, gthDepartmentId, 'H' LocType    
FROM meiGOdownTransferHeader LEFT OUTER JOIN aGodown    
ON gthFromGodownId = GodownId    
WHERE gthCancelled = 0 AND gthTransFinished = 0    
    
UNION ALL    
    
SELECT 'Goods Arrival To Shop', gahArrivalId, gahArrivalNo, gahArrivalDate,     
gahShopId, ShopName, gahDepartmentId, 'S' LocType    
FROM LOsGoodsArrivaltoShopHeader LEFT OUTER JOIN aShops    
ON gahShopId = ShopId    
WHERE gahCancelled = 0    
AND gahTransFinished = 0    
    
UNION ALL    
    
--SELECT 'Request To Shop', srhRequestId, srhRequestNo, srhRequestDate,     
--srhShopId, ShopName, Departmentid , 'S' LocType    
--FROM mesRequestToShopHeader LEFT OUTER JOIN aShops    
--ON srhShopId = aShops.ShopId    
--WHERE srhCancelled = 0    
--AND srhTransFinished = 0    
    
--UNION ALL    
    
SELECT 'Request To HQ', grhRequestId, grhRequestNo, grhRequestDate,     
grhShopId, ShopName, departmentid, 'S' LocType    
FROM mosGoodsRequestHeader LEFT OUTER JOIN aShops    
ON grhShopId = aShops.ShopId    
WHERE grhCancel = 0    
AND grhTransFinished = 0    
    
--UNION ALL    
    
--SELECT 'Transfer Out', tohId, tohNo, tohDate, tohShopId,    
--ShopName, tohDepartmentid, 'S' LocType    
--FROM mesTransferOutHeader LEFT OUTER JOIN aShops    
--ON tohShopId = aShops.ShopId    
--WHERE tohCancelled = 0    
--AND tohTransFinished = 0    
    
UNION ALL    
    
SELECT 'Transfer In', tihId, tihNo, tihDate, tihShopId,    
ShopName, tihDepartmentid, 'S' LocType    
FROM losTransferInHeader LEFT OUTER JOIN aShops    
ON tihShopId = aShops.ShopId    
WHERE tihCancel = 0    
AND tihTransFinished = 0    
    
UNION ALL    
    
SELECT 'Shop To Godown Transfer', dghID, dghNo, dghDate, dghShopId,    
ShopName, dghDepartmentid, 'S' LocType    
FROM mesDespatchtoGodownHeader LEFT OUTER JOIN aShops    
ON dghShopid = aShops.ShopId    
WHERE dghCancelled = 0 AND dghTransFinished = 0    
    
UNION ALL    
    
SELECT 'Special Invoice', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopId,    
ShopName, ihDepartmentid, 'S' LocType FROM losSpecialInvoiceHeader LEFT OUTER JOIN aShops    
ON ihShopId = aShops.ShopId WHERE ihCancelled = 0 AND ihTransFinished = 0 

--Ref.No:1------------------------------START----------------------------------------------------   
    
UNION ALL    

SELECT 'Local Purchase', lphBillID, lphBillNo, lphBillDate, lphShopID,  
ShopName, lphDepartmentID, 'S' LocType FROM loslocalpurchaseheader LEFT OUTER JOIN aShops  
ON lphShopID = aShops.ShopId WHERE lphCancelled = 0 AND lphConfirmed = 0 

UNION ALL    

SELECT 'Warrenty Claim', wchID, wchNo, wchDate, wchShopID,  
ShopName, DepartmentID, 'S' LocType FROM losWarrentyClaimHeader LEFT OUTER JOIN aShops  
ON wchShopID = aShops.ShopId WHERE wchCancelled = 0 AND wchConfirmed = 0 and wchType='WC'

UNION ALL    

SELECT 'Business Promotion', wchID, wchNo, wchDate, wchShopID,  
ShopName, DepartmentID, 'S' LocType FROM losWarrentyClaimHeader LEFT OUTER JOIN aShops  
ON wchShopID = aShops.ShopId WHERE wchCancelled = 0 AND wchConfirmed = 0 and wchType='BP'

UNION ALL    

SELECT 'Hire Purchase Invoice', hpqhQuotationID, hpqhQuotationNo, hpqhQuotationDate, hpqhShopID,  
ShopName, DepartmentID, 'S' LocType FROM losHpInvoiceHeader LEFT OUTER JOIN aShops  
ON hpqhShopID = aShops.ShopId WHERE hpqhCancel = 0 AND hpqhConfirmed = 0  

UNION ALL    
 
SELECT 'InHouse Return/Exchanged', IHRHID, IHRHNo, IHRHDate, IHRHShopID,  
ShopName, DepartmentID, 'S' LocType FROM LOs_InHouseCons_ReturnHeader LEFT OUTER JOIN aShops  
ON IHRHShopID = aShops.ShopId WHERE IHRHCancelled = 0 AND IHRHConfirmed = 0 

UNION ALL    

SELECT 'MerGing', lshID, lshNo, lshDate, lshShopID,  
ShopName, DepartmentID, 'S' LocType FROM losMergeHeader LEFT OUTER JOIN aShops  
ON lshShopID = aShops.ShopId WHERE lshCancelled = 0 AND lshTransFinished = 0  

UNION ALL    

SELECT 'Purchase Return', WhID, WhNo, WhDate, whShopID,  
ShopName, DepartmentID, 'S' LocType FROM losPurchaseReturnheader LEFT OUTER JOIN aShops  
ON whShopID = aShops.ShopId WHERE WhCancelled = 0 AND whtransfinished = 0  

UNION ALL    

--Invoice confirmation is not using in program 
--SELECT 'Credit Invoice', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopID,  
--ShopName, DepartmentID, 'S' LocType FROM losinvoiceheader LEFT OUTER JOIN aShops  
--ON ihShopID = aShops.ShopId WHERE ihCancelled = 0 AND ihtransfinished = 0 and ihType='I' 

--UNION ALL

SELECT 'Purchase Quotation', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopID,  
ShopName, DepartmentID, 'S' LocType FROM losinvoiceheader LEFT OUTER JOIN aShops  
ON ihShopID = aShops.ShopId WHERE ihCancelled = 0 AND ihtransfinished = 0 and ihType='Q' 

UNION ALL

SELECT 'Purchase Order', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopID,  
ShopName, DepartmentID, 'S' LocType FROM losinvoiceheader LEFT OUTER JOIN aShops  
ON ihShopID = aShops.ShopId WHERE ihCancelled = 0 AND ihtransfinished = 0 and ihType='P' 

UNION ALL

SELECT 'Purchase Request', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopID,  
ShopName, DepartmentID, 'S' LocType FROM losinvoiceheader LEFT OUTER JOIN aShops  
ON ihShopID = aShops.ShopId WHERE ihCancelled = 0 AND ihtransfinished = 0 and ihType='R'    

UNION ALL

SELECT 'Shop Consumption', WhID, WhNo, WhDate, whShopID,  
ShopName, DepartmentID, 'S' LocType FROM LOsWriteOffHeader LEFT OUTER JOIN aShops  
ON whShopID = aShops.ShopId WHERE WhCancelled = 0 AND whverified = 0 and whtype='I'

UNION ALL

SELECT 'Dummy POS', poshBillID, poshBillNo, poshBillDate, poshShopID,  
ShopName, DepartmentID, 'S' LocType FROM LOsPosdummyHeader LEFT OUTER JOIN aShops  
ON poshShopID = aShops.ShopId WHERE poshCancelled = 0 AND poshconfirmed = 0  

UNION ALL

SELECT 'SerialNo Verification', svhID, svhNo, svhDate, svhShopID,  
ShopName, DepartmentID, 'S' LocType FROM losSerialNoVerificationHeader LEFT OUTER JOIN aShops  
ON svhShopID = aShops.ShopId WHERE svhCancel = 0 AND cofirmed = 0 

UNION ALL

SELECT 'Stand By Issue', ishIssueID, ishIssueNo, ishDate, ishShopID,  
ShopName, DepartmentID, 'S' LocType FROM losSerStandByIssueHeader LEFT OUTER JOIN aShops  
ON ishShopID = aShops.ShopId WHERE ishCancelled = 0 AND ishConfirmed = 0  

UNION ALL

SELECT 'Special Invoice Quotation', IhInvoiceID, IhInvoiceNo, IhInvoiceDate, IhShopID,  
ShopName, DepartmentID, 'S' LocType FROM losSIQuotationHeader LEFT OUTER JOIN aShops  
ON IhShopID = aShops.ShopId WHERE IhCancelled = 0 AND ihTransFinished = 0  

UNION ALL

SELECT 'Request To Shop', srhRequestId, srhRequestNo, srhRequestDate,     
srhShopId, ShopName, Departmentid , 'S' LocType    
FROM mesRequestToShopHeader LEFT OUTER JOIN aShops    
ON srhShopId = aShops.ShopId    
WHERE srhCancelled = 0    
AND srhTransFinished = 0 and srhType='r'

UNION ALL

SELECT 'Inter Division Sales Request', srhRequestId, srhRequestNo, srhRequestDate,     
srhShopId, ShopName, Departmentid , 'S' LocType    
FROM mesRequestToShopHeader LEFT OUTER JOIN aShops    
ON srhShopId = aShops.ShopId    
WHERE srhCancelled = 0    
AND srhTransFinished = 0 and srhType='s'

UNION ALL

SELECT 'Transfer Out', tohId, tohNo, tohDate, tohShopId,    
ShopName, tohDepartmentid, 'S' LocType    
FROM mesTransferOutHeader LEFT OUTER JOIN aShops    
ON tohShopId = aShops.ShopId    
WHERE tohCancelled = 0    
AND tohTransFinished = 0  and tohType='TO'  

UNION ALL

SELECT 'Inter Division Sales', tohId, tohNo, tohDate, tohShopId,    
ShopName, tohDepartmentid, 'S' LocType    
FROM mesTransferOutHeader LEFT OUTER JOIN aShops    
ON tohShopId = aShops.ShopId    
WHERE tohCancelled = 0    
AND tohTransFinished = 0  and tohType='IS' 

--Ref.No:1-------------------------------END-----------------------------------------------   

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_028
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

/****** Object:  View [dbo].[vwUnPostedShopTransactions]    Script Date: 03/24/2012 17:23:17 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwUnPostedShopTransactions]'))
DROP VIEW [dbo].[vwUnPostedShopTransactions]
GO



/****** Object:  View [dbo].[vwUnPostedShopTransactions]    Script Date: 03/24/2012 17:23:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- ==================================================================       
-- Created by : MANUNADH. U    
-- Created on : 23/03/2012
-- Comments   : To create a report for showing unposted shop transactions
-- =================================================================       
create VIEW [dbo].[vwUnPostedShopTransactions] AS  
SELECT 'POS' TransactionType,poshbillid TransactionId,poshbillno TransactionNo,poshbilldate TransactionDate,
	poshDepartmentid Departmentid,ph.poshshopid LocationId,S.ShopName LocationName
FROM losposheader ph 
	LEFT OUTER JOIN Ashops S ON ph.poshshopid = S.ShopID            
WHERE ph.poshcancellED = 0 and ph.poshpostED = 0 

UNION ALL
SELECT 'Goods Return Note',grnh.grnhGoodsReturnNoteID,grnhGoodsReturnNoteNo,grnhGoodsReturnNoteDate,           
	grnhDepartmentId,grnh.grnhShopid,S.ShopName
FROM LOsGoodsReturnNoteHeader grnh           
	LEFT OUTER JOIN Ashops S ON grnh.grnhShopid = S.ShopID
WHERE  grnhPosted = 0 and grnhCancel = 0    

UNION ALL
SELECT 'Goods Exchange',sehExchangeId,sehExchangeNo,sehExchangeDate,sehDepartmentID,sehShopID,S.ShopName
FROM losposExchangeHeader               
	LEFT OUTER JOIN Ashops S ON sehShopID = S.ShopID
WHERE sehcancelled = 0 and sehposted = 0 

UNION ALL
SELECT 'Invoice',ihInvoiceId,ihinvoiceno,ihinvoicedate,ihdepartmentid,ihShopID,S.ShopName
FROM losinvoiceheader I
	LEFT OUTER JOIN Ashops S ON I.ihShopID = S.ShopID              
WHERE ihcancelled =0 and ihposted =0 and ihproforma = 0 and ihcashinvoice =0 and ihtype ='i'           

UNION ALL
SELECT 'Service Invoice',aiInvoiceID,aiInvoiceNo,aiInvoiceDate,aiDepartmentID,aiShopID,S.ShopName
FROM losAccountsInvoiceHeader 
	LEFT OUTER JOIN Ashops S ON aiShopID = S.ShopID              
WHERE aiCancelled = 0 and aiPosted = 0 and aiProforma = 0  

UNION ALL

SELECT 'Direct Invoice', ihinvoiceId, ihinvoiceno, ihinvoicedate,ihdepartmentId,IhShopID,S.ShopName
FROM losSpecialInvoiceHeader               
	LEFT OUTER JOIN Ashops S ON IhShopID = S.ShopID              
WHERE ihcancelled = 0 and ihtransfinished = 1 and ihposted = 0 and ihproforma = 0

UNION ALL

SELECT 'Payments', phPaymentID, phpaymentno, phpaymentdate,phDepartmentID,phShopID,S.ShopName 
FROM LOsPaymentVoucherHeader 
	LEFT OUTER JOIN Ashops S ON phShopID = S.ShopID
WHERE phpostED =0 and phcancellED =0 

UNION ALL
SELECT 'Local Purchase',lphbillid,lphbillno,lphBillDate,lphdepartmentid,lphShopID,S.ShopName                            
FROM losLocalPurchaseHeader            
	LEFT OUTER JOIN Ashops S ON lphShopID = S.ShopID                  
WHERE lphcancellED = 0 and lphpostED = 0 and lphConfirmed=1 

UNION ALL
SELECT 'Goods Arrival To Shop',gahArrivalID,gahArrivalNo, gahArrivalDate, gahdepartmentid,gahShopid,S.ShopName
FROM  LosGoodsArrivaltoShopHeader ga       
	LEFT OUTER JOIN Ashops S ON gahShopid = S.ShopID  
WHERE  gahCancelled = 0 and gahposted = 0 and gahTransFinished = 1       

UNION ALL
SELECT 'Transfer In',TIHID,TIHNO,TIHDate,tihdepartmentid,TIHShopid,S.ShopName
FROM LOSTransferinheader tinh  
	LEFT OUTER JOIN Ashops S ON TIHShopid = S.ShopID  
WHERE  TIHcancel =0 and TIHPosted =0 and TIHTransFinished = 1 and TIHType = 'TI'    

UNION ALL
SELECT 'Transfer Out',ToHID, ToHNO, ToHDate,tohdepartmentid ,TOHShopid,S.ShopName
FROM mestransferoutheader tinh     
	LEFT OUTER JOIN Ashops S ON TOHShopid = S.ShopID  
WHERE  ToHcancelled =0 and ToHPosted =0 and ToHTransFinished = 1 and tohtype ='TO'    

UNION ALL

SELECT 'Despatch To Godown',dgHID,dgHNO,dgHDate,dghdepartmentid,dghShopID,S.ShopName
FROM mesDespatchToGodownHeader tinh   
	LEFT OUTER JOIN Ashops S ON dghShopID = S.ShopID  
WHERE  dgHcancelled = 0 and dgHPosted = 0 and dgHTransFinished = 1   

UNION ALL
SELECT 'Reexport',rehExportId,rehExportNo,rehExportDate,rehdepartmentid,rehShopID,S.ShopName
FROM losExportHeader   
	LEFT OUTER JOIN Ashops S ON rehShopID = S.ShopID  
WHERE rehcancelled =0 and rehposted =0 and rehcashinvoice =0 and rehtype ='i'   

UNION ALL

SELECT 'Inhouse Consumption',whID, whno, whdate,whdepartmentid,whShopID,S.ShopName                   
FROM loswriteoffheader 
	LEFT OUTER JOIN Ashops S ON whShopID = S.ShopID  
WHERE WhCancelled =0 and whposted =0 and whtype='I' and whVerified=1                    

UNION ALL
SELECT 'Inhouse Return',IHRHID,IHRHNo,IHRHDate,IHRHdepartmentid,IHRHShopID,S.ShopName   
FROM LOs_InHouseCons_ReturnHeader 
	LEFT OUTER JOIN Ashops S ON IHRHShopID = S.ShopID 
WHERE IHRHCancelled =0 and IHRHposted=0 and IHRHConfirmed=1                      
  
UNION ALL
SELECT 'Stock Write Off Shop',whId,whno,whdate,whdepartmentId,whShopID,S.ShopName
FROM loswriteoffheader   
	LEFT OUTER JOIN Ashops S ON whShopID = S.ShopID 
WHERE whcancellED =0 AND whposted =0 and whType='W'  

UNION ALL

SELECT 'Stock Verification Shop',svhId, svhno, svhdate,svhdepartmentId,svhShopId,S.ShopName
FROM losstockverificationheader   
	LEFT OUTER JOIN Ashops S ON svhShopId = S.ShopID 
WHERE svhcancelled =0 and svhposted =0   

--UNION ALL 
--SELECT 'Recovery Shop',srId,srtransno,srdate,srDepartmentId,srShopID,S.ShopName
--FROM losStockRecovery r
--	LEFT OUTER JOIN Ashops S ON R.srShopID = S.ShopID 
--WHERE srposted =0     

UNION ALL
SELECT 'Booking Advance',serbookhid,serbookhinspectionno,serbookhInspectionDate,serbookhdepartmentid,
	serbookhshopid,S.ShopName
FROM losservicebookingheader bk
	LEFT OUTER JOIN Ashops S ON serbookhshopid = S.ShopID
WHERE serbookhinpcancelled = 0 and serbookhposted = 0 and serbookadvanceamount > 0 and serbookhstatus <>'n'  

UNION ALL
SELECT 'Booking Invoice',li.serinvhid,li.serinvno,li.serinvhdate,li.serinvhdepartmentid,li.serinvhshopid,S.ShopName        
FROM losserviceinvheader li                     
	LEFT OUTER JOIN Ashops S ON li.serinvhshopid = S.ShopID         
WHERE li.serinvhcancelled =0 AND li.serinvhposted =0 

UNION ALL
SELECT 'Booking Cancellation',bkcancellId,bkcancellno,bkcancelldate,0,bkcancellshopid,S.ShopName
from losbookingcancellation 
	LEFT OUTER JOIN Ashops S ON bkcancellshopid = S.ShopID     
where bkcancellId = 0 and  bkcancellcancelled=0 AND bkcancellposted=0 
 
UNION ALL 
SELECT 'Inter Department Sales',ToHID,ToHNO,ToHDate,tohdepartmentid,ToHShopid,S.ShopName  
FROM mestransferoutheader tinh   
	LEFT OUTER JOIN Ashops S ON ToHShopid = S.ShopID     
WHERE  ToHcancelled =0 AND ToHPosted =0 AND ToHTransFinished = 1 AND tohType ='IS'     

UNION ALL 
SELECT 'Inter Department Purchase',TIHID,TIHNO,TIHDate,tihdepartmentid,TIHShopid,S.ShopName 
FROM LOSTransferinheader tinh   
	LEFT OUTER JOIN Ashops S ON TIHShopid = S.ShopID 
WHERE  TIHcancel =0 and TIHPosted =0 and TIHTransFinished = 1 and TIHType = 'IP'  

UNION ALL

SELECT 'Shop Debit/Credit Note',losDCNId,losDCNNo,losDCNDate,losdcndepartmentid,losDCNShopid,S.ShopName
from losDebitCreditNote  
	LEFT OUTER JOIN Ashops S ON losDCNShopid = S.ShopID    
where losDCNPosted = 0 and losDCNCancelled = 0 
  
UNION ALL 
SELECT ' Agreement',mghAgreementID, mghAgreementNo,mghAgreementDate,mghDepartmentid, mghShopId,S.ShopName
FROM losApartmentAgreementHeader ah  
	LEFT OUTER JOIN Ashops S ON mghShopId = S.ShopID
WHERE mghCancelled = 0 and mghPosted = 0 and mghadvdate is not null  

UNION ALL
SELECT 'Utility Bill Details',tbhBillId,tbhBillNo,tbhBillDate,tbhDepartmentID,tbhShopId,S.ShopName
from losTenantServiceBillHeader 
	LEFT OUTER JOIN Ashops S ON tbhShopId = S.ShopID
where tbhPosted=0 and tbhCancelled=0 

UNION ALL
SELECT 'Room Billing',abhBillId ,abhBillNo,abhBillDate,abhDepartmentid,abhSHopID,S.ShopName
FROM losApartmentBillHeader  
	LEFT OUTER JOIN Ashops S ON abhSHopID = S.ShopID
WHERE abhPosted=0 and abhCancelled=0  
   
UNION ALL   
SELECT 'Check Out Returns',chID,chNo,chDate,ChDepartmentID,chShopID,S.ShopName
FROM losApartmentCheckOut   
	LEFT OUTER JOIN Ashops S ON chShopID = S.ShopID
WHERE chCancelled = 0 and chPosted = 0 and (chDepositAmount>0 or chAvaliedAmount>0)  

UNION ALL
SELECT 'HP Invoices',hpqhQuotationID,hpqhQuotationNo,hpqhQuotationDate,0, hpqhShopId, S.ShopName         
FROM loshpinvoiceheader     
	LEFT OUTER JOIN Ashops S ON hpqhShopId = S.ShopID        
WHERE hpqhcancel =0 and hpqhposted =0  and hpqhConfirmed=1 and hpqhType='I'  

UNION ALL             
SELECT 'HP Shop Receipts',hprhReceiptID,hprhReceiptNo,hprhReceiptDate,0,hprhShopID,S.ShopName
FROM loshpReceiptheader         
	LEFT OUTER JOIN Ashops S ON hprhShopID = S.ShopID  
WHERE hprhCancel=0 and hprhPosted=0 and hprhReceiptType='S' 

UNION ALL
SELECT 'HP Shop Down Payment',hprhReceiptID,hprhReceiptNo,hprhReceiptDate,0,hprhShopID,S.ShopName
FROM loshpReceiptheader     
	LEFT OUTER JOIN Ashops S ON hprhShopID = S.ShopID  
WHERE hprhCancel=0 and hprhPosted=0 and hprhReceiptType='A' 

UNION ALL
SELECT 'HP Resale',hphResaleID,hphResaleNo,hphReSaleDate,0,hphShopID,S.ShopName
FROM  losHpReSaleHeader       
	LEFT OUTER JOIN Ashops S ON hphShopID = S.ShopID 
WHERE hphCancel =0 and hphposted =0  

UNION ALL
SELECT 'HP Repossession',hprhRepossessionID,hprhRepossessionNo,hprhRepossessionDate,0,hprhShopId,S.ShopName
FROM losHpRepossessionHeader     
	LEFT OUTER JOIN Ashops S ON hprhShopId = S.ShopID 
WHERE hprhCancel =0 and hprhposted =0  

UNION ALL
SELECT 'Shop Purchase Return',whID,whNo,whDate,whDepartmentId,whShopId,S.ShopName
FROM losPurchaseReturnHeader 
	LEFT OUTER JOIN Ashops S ON whShopID = S.ShopID 
WHERE whCancelled = 0 And whPosted = 0 And whType ='P'  
  
UNION ALL
SELECT 'Food and Beverages Bill',poshBillID,poshBillNo,poshBillDate,poshDepartmentid,poshShopID,S.ShopName
FROM losPosFandBHeader h    
	LEFT OUTER JOIN Ashops S ON poshShopID = S.ShopID     
WHERE h.poshCancelled=0 and h.poshPosted = 0 

UNION ALL
SELECT 'Goods Arrival Inventory',ahArrivalId,ahArrivalNo,ahArrivalDate,ahdepartmentid,
	CASE WHEN (ahShopID IS NULL AND AHGodownID IS NULL) THEN 0 
		WHEN ahShopID IS NULL THEN AHGodownID ELSE ahShopID END, 
	CASE WHEN (ahShopID IS NULL AND AHGodownID IS NULL) THEN 'HQ' 
		WHEN ahShopID IS NULL THEN G.GodownName ELSE S.ShopName END	
FROM LOiArrivalHeader ga     
	LEFT OUTER JOIN Ashops S ON ahShopID = S.ShopID 
	LEFT OUTER JOIN aGodown G ON G.GodownID=AHGodownID
WHERE ahCancelled = 0 and ahPosted = 0 and ahTransFinished = 1     

UNION ALL
SELECT 'Goods Dispatch to Shop',dhDespatchId, dhdespatchno, dhdespatchdate,dhDepartmentId,dhShopID,S.ShopName
FROM meiDespatchToShopHeader     
	LEFT OUTER JOIN Ashops S ON dhShopID = S.ShopID 
WHERE dhCancelled = 0 and dhPosted =0 and dhTransFinished=1

UNION ALL
SELECT 'Stock Write off Inventory',whID, whno, whdate,whdepartmentid,whGodownID,G.GodownName
FROM loiwriteoffheader           
	LEFT OUTER JOIN aGodown G ON G.GodownID=whGodownID
WHERE whcancellED = 0 and whposted = 0 and whType = 'W'          
  
UNION ALL  
SELECT 'Stock Verification Inventory',svhid,svhno,svhdate,svhdepartmentid,svhGodownid,G.GodownName
FROM loiStockVerificationHeader   
	LEFT OUTER JOIN aGodown G ON G.GodownID=svhGodownid
WHERE svhcancelled =0 and svhposted =0   

UNION ALL
SELECT 'Recovery Inventory',srID,srtransno,srDate,0,srGodownID,G.GodownName
FROM loiStockRecovery i
	LEFT OUTER JOIN aGodown G ON G.GodownID=srGodownID
WHERE srposted = 0   

UNION ALL
SELECT 'Special Despatch',dhDespatchId, dhdespatchno, dhdespatchdate,dhDepartmentId,dhgodownid,G.GodownName
FROM meiSpecialDespatchToShopHeader 
	LEFT OUTER JOIN aGodown G ON G.GodownID=dhgodownid
WHERE dhCancelled = 0 and dhposted = 0     

UNION ALL
SELECT 'Godown to Godown Transfer',gthDespatchID,gthDespatchNo,gthDespatchDate,gthDepartmentId,gthFromGodownId,
	G.GodownName
FROM MEiGodownTransferHeader tinh 
	LEFT OUTER JOIN aGodown G ON G.GodownID=gthFromGodownId  
WHERE gthCancelled = 0 and gthPosted = 0 and gthTransFinished = 1   

UNION ALL
SELECT 'Asset Transfer',whID, whno, whdate,whDepartmentId,whGodownID,G.GodownName
FROM loiWriteOffHeader   
	LEFT OUTER JOIN aGodown G ON G.GodownID=whGodownID
WHERE whCancelled = 0 and whPosted = 0  and whType ='A'  

UNION ALL
SELECT 'Purchase Return',whID, whNo, whDate,whDepartmentId,whGodownId,G.GodownName
FROM loiWriteOffHeader 
	LEFT OUTER JOIN aGodown G ON G.GodownID=whGodownID
WHERE whCancelled = 0 and whPosted = 0 and whType ='R'  

UNION ALL
SELECT 'HQ Stock Write Off',swID,swTransCode,swDate,0, 
	CASE WHEN swShopID IS NULL THEN swGodownID ELSE swShopID END ,
	CASE WHEN swShopID IS NULL THEN G.GodownName ELSE S.ShopName  END
FROM moStockWriteOffHQ 
	LEFT OUTER JOIN Ashops S ON swShopID = S.ShopID 
	LEFT OUTER JOIN aGodown G ON G.GodownID=swGodownID
WHERE swposted =0   

UNION ALL
SELECT 'Business Promotion',wchID,wchNo,wchDate,0,wchSHOPID,S.ShopName    
FROM losWarrentyClaimHeader      
	LEFT OUTER JOIN Ashops S ON wchSHOPID = S.ShopID
    WHERE wchType='BP' and wchposted=0 and wchCancelled=0 and wchConfirmed=1 

UNION ALL
SELECT 'Warrenty Claim',wchID,wchNo,wchDate,0,wchShopID,S.ShopName
FROM losWarrentyClaimHeader
	LEFT OUTER JOIN Ashops S ON wchSHOPID = S.ShopID
WHERE wchType='WC' and wchposted=0 and wchCancelled=0 and wchConfirmed=1 


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_030
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


/****** Object:  View [dbo].[vwShopBincardAudit]    Script Date: 03/27/2012 11:51:21 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBincardAudit]'))
DROP VIEW [dbo].[vwShopBincardAudit]
GO

GO

/****** Object:  View [dbo].[vwShopBincardAudit]    Script Date: 03/27/2012 11:51:23 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- Modified By   : Benzigar 23092008                              
-- Modified Date : 23092008                              
-- Comment       : Added Business Promotion/Warrenty claim                    
-- =====================================                    
-- Upgraded By : Regin T.                    
-- Upgraded On : 22-07-2010                    
-- Upgrade     : An outer Group By clause was used to change                     
--   the position of TransId and TransNo fields.                    
--   This Group By clause casued delay. So I removed it, and                     
--   changed the position of fields in all union all parts.                    
--   Old position: TransId, TransNo                    
--   New position: TransNo, TransId                    
-- =====================================                    
-- Upgraded By : Regin T.                  
-- Upgraded On : 18-09-2010                    
-- Upgrade     : Added FandB Bill                  
-- =====================================                  
-- Upgraded By : NIDHEESH P.V.                  
-- Upgraded On : 09-02-2011                    
-- Upgrade     : Added In-House Return                 
-- =====================================             
--------------------------------------------------------------------------------        
-- Modified by          : MANUNADH.U ON : 11/05/2011        
-- Comments             : Added the column From/To for Bincard Audit report                      
--------------------------------------------------------------------------------             
 --------------------------------------------------------------------------------        
-- Modified by          : AADYAKUMAR.D.V ON : 31/05/2011        
-- Comments             : Bug fixed in transfer out      
--------------------------------------------------------------------------------    
--Modified by          : Nidheesh P V
--Modified on		   : 6/07/2011        
--Comments             : Added In-House Consumption part seperately.
--Modified Area        : All Interfaces where stock effects
--Referenc No          : Ref-No1    
--------------------------------------------------------------------------------             
-- Referenc No  : Ref-No2
-- Modified by	: MANUNADH.U      
-- Modified on	: 26/03/2012              
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1      
--------------------------------------------------------------------------------             
CREATE VIEW [dbo].[vwShopBincardAudit]  AS           
--arrival from godown           
select h.gahshopid ShopId, d.gaditemid ItemId, h.gaharrivaldate sDate,h.gaharrivalno TransNo,h.gaharrivalid TransId,        
 convert(numeric(18,3),isnull(sum(d.gadItemGoodQuantityArrived),0)) TransQty,'Arrival From Godown' [Type],         
 1 Mode, UpdateTime, gadCostprice CostPrice,gadCostPrice * gahdepexrate DepCostPrice,         
 gadCostPrice * gahconexrate ConCostPrice,        
 --(case when g.GodownName IS null then 'HQ' else g.GodownName end  + '/' + s.ShopName)  as 'From/To'         
 (case when g.GodownName IS null then 'HQ' else g.GodownName end  )  as 'From/To'                      
from losgoodsarrivaltoshopheader h        
 left outer join aGodown g on g.GodownID=h.gahDespatchedGodownID        
 left outer join ashops s on s.ShopID=h.gahShopid,losgoodsarrivaltoshopdetail d        
where h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and h.gahtransfinished=1             
group by  h.gahshopid, h.gaharrivaldate, h.gaharrivalid,gaharrivalno, d.gaditemid,updatetime, gadCostprice,         
 gahdepexrate, gahconexrate,g.GodownName,s.ShopName                                              
                                        
----GOODS RETURN TO SHOPS FROM CREDIT INVOICES                                        
union all                                        
                                        
select grn.grnhShopid, grd.GRNDItemID, GrnhGoodsreturnnoteDate sdate,GrnhGoodsreturnnoteNO transno,         
 GrnhGoodsreturnnoteID transid, convert(numeric(18,3),isnull(GRNDQuantity,0)) transqty,'Goods Return',1 as mode,        
 updatetime, grncostprice,grncostprice * grnhdepexrate depCostPrice, grncostprice * grnhExchangeRate ConCostPrice,        
 '' as 'From/To'        
from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd                                        
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid = grd.GRNDShopid and GrnhCancel=0         
 and GRNDDamaged=0        
                                        
union all      
                                        
--transfer in                       
select h.tihshopid shopid,  d.tiditemid itemid, h.tihdate sdate, h.tihno, h.tihid,                                         
 convert(numeric(18,3),sum(d.TIDrecievedgoodqty)) as TinQty, 'Transfer In' TYpe, 1 mode,updatetime, tidCostPrice,         
 tidCostPrice * tihdepexrate depCostPrice, tidCostPrice * tihconexrate ConCostPrice ,s.ShopName as 'From/To'                                        
from lostransferinheader h        
 left outer join ashops s on s.ShopID=h.TIHfromshopID,lostransferindetail d         
where h.tihid=d.tidid and h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1                    
group by h.tihshopid, h.tihdate,  h.tihid, h.tihno, d.tiditemid ,updatetime, tidCostPrice ,                                         
 tihdepexrate, tihconexrate,s.ShopName                                        
                                        
union all           
                                        
--recovery add                                        
select sr.srshopid, sr.sritemid, sr.srdate sdate, 'Rec' + convert(varchar(50), sr.srid) srno, sr.srid,                                                             
 convert(numeric(18,3),isnull(sum(sr.sraddstock),0))  as recAdd, 'Recovery Plus' Type,1 Mode,updatetime,         
 srCostPrice,srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,'' as 'From/To'          
from losstockrecovery sr                     
group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,srCostPrice, srdepexrate, srconexrate                                         
having isnull(sum(sr.sraddstock),0) >0        
                                        
union all                                        
                                        
--stock verification add                                        
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,        
 convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,'Verification Plus' Type, 1 mode,        
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice        
 ,'' as 'From/To'                                          
from  losstockverificationheader, losstockverificationdetail         
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and          
 left(svhFutureVc, 1) <> 't'                       
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,svdCostPrice, svhdepexrate, svhconexrate                                        
                                  
union all                                        
                                        
--TOTAL stock verification add                                        
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,        
 convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,'Verification Plus' Type, 1 mode,        
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice         
 ,'' as 'From/To'                                         
from  losstockverificationheader, losstockverificationdetail         
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and          
 left(svhFutureVc, 2) = 'tc'                      
group by svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,svdCostPrice, svhdepexrate, svhconexrate                                        
                                              
union all                                        
                                        
--exchange in                                        
                                        
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeno, sehexchangeid,                      
 convert(numeric(18,3),sum(isnull(sedExchangeQty,0)))  as exchangedin, 'Exchanged In' Type,1 mode,updatetime,         
 sedCostPrice,sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,'' as 'From/To'             
from losposexchangeheader, losposexchangedetail         
where sedExchangeid=sehExchangeID and sedShopID=sehShopid and sedBillorExchange='B' and SEHCANCELLED=0                                        
 and isnull(sedExchangeQty,0) >0                                        
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,                                         
 sedCostPrice, sehDepExrate, sehExchangerate                                          
                                        
union all                                        
                                        
--local purchase                                      
select lphShopid, lpditemid, lphbilldate, lphBillNo, lphBillid,                                          
	convert(numeric(18,3),sum(isnull(lpdItemQuantity,0))) localpurchase,'Local Purchase' Type, 1 mode,updatetime,         
	(lpdItemUnitPrice/ lpdItemQuantity),(lpdItemUnitPrice/ lpdItemQuantity) * lphdepexrate depCostPrice,                                         
	(lpdItemUnitPrice/ lpdItemQuantity)* lphExchangerate ConCostPrice ,'' as 'From/To'                                            
from loslocalpurchasedetail, loslocalpurchaseheader         
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphConfirmed=1--Ref-No2                     
group by lphshopid, lphBillid, lphBillNo,lphbilldate, lpditemid,updatetime, lpdItemUnitPrice, lpdItemQuantity,         
	lphdepexrate,lphExchangerate                       
                                        
union all                                        
                                        
--write off                                        
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whno, wh.whid,                                         
 convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty, 'Write off' TYpe, -1 mode,updatetime, wdCostPrice,                                         
 wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'' as 'From/To'                                         
from loswriteoffheader wh, loswriteoffdetail wd                                        
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and  whtype<>'I' --Ref-No1                  
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,                                         
 whDepExrate, whConExrate                                        
                                        
union all  

--InHouse Cons   --Ref-No1                                     
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whno, wh.whid,                                         
 convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty, 'In-House Cons' TYpe, -1 mode,updatetime, wdCostPrice,                                         
 wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'' as 'From/To'                                         
from loswriteoffheader wh, loswriteoffdetail wd                                        
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and  whtype='I' and whVerified=1                     
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,                                         
 whDepExrate, whConExrate                                        
                                        
union all                                        
                                      
                                        
--Despatch                                        
select dd.dgdshopid, dd.dgditemid, dh.dghDate sdate, dh.dghNo, dh.dghid,                                         
 convert(numeric(18,3),sum(dd.dgddespatchedgoodqty)) as despatchqty,'Despatch To Godown' TYpe, -1 mode,updatetime,        
 dgdCostPrice,dgdCostPrice * dghdepexrate depCostPrice, dgdCostPrice * dghConExrate ConCostPrice        
 ,g.GodownName  as 'From/To'                                                      
from mesdespatchtogodownheader dh        
 left outer join aGodown g on g.GodownID=dh.dghGodownID,mesdespatchtogodowndetail dd                                         
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0                           
 and dghtransfinished = 1 -- for the concept of stock updation after transaction finish                                         
group by dd.dgdshopid, dh.dghdate, dh.dghid, dh.dghNo,dd.dgditemid,updatetime,                                         
 dgdCostPrice, dghdepexrate, dghconexrate,g.GodownName                                        
                                       
union all      
    
----Transferout                                      
--select todshopid, toditemid, tohDate sdate, tohno, tohid,                                       
-- convert(numeric(18,3),sum(todissuedgoodqty)) as ToutQty , 'Transfer Out' Type,-1 mode,updatetime, todCostPrice,                                       
-- todCostPrice * tohdepexrate depCostPrice, todCostPrice * tohConExrate ConCostPrice,s.ShopName as 'From/To'                                      
--from mestransferoutheader h      
-- left outer join ashops s on s.ShopID=h.TOHtoShopid,lostransferindetail d ,mestransferoutdetail        
--where tohid=todid and Tohshopid=todshopid and tohcancelled=0                                      
-- and tohtransfinished = 1 -- for the concept of stock updation after transaction finish                                       
--group by todshopid, tohdate, tohid, tohno, todItemid,updatetime, todCostPrice,                                       
-- tohdepexrate, tohConExrate,s.ShopName                                          
                                        
--Transferout                                        
select todshopid, toditemid, tohDate sdate, tohno, tohid,                                         
convert(numeric(18,3),sum(todissuedgoodqty)) as ToutQty ,      
'Transfer Out' Type,-1 mode,updatetime, todCostPrice,                                         
todCostPrice * tohdepexrate depCostPrice, todCostPrice * tohConExrate ConCostPrice,s.ShopName as 'From/To'      
from mestransferoutdetail inner join mestransferoutheader h       
on tohid=todid and Tohshopid=todshopid and tohcancelled=0 and tohtransfinished = 1 inner join       
ashops s on s.ShopID=h.TOHtoShopid --inner join lostransferindetail on TODitemid=TIDitemID       
--where TOHShopid=5 and TODitemid=8626       
group by todissuedgoodqty,tohid,todshopid, tohdate, tohid, tohno, todItemid,updatetime, todCostPrice,                                         
tohdepexrate, tohConExrate,s.ShopName        
                                    
                                        
union all                                        
                                        
--recovery minus                                        
select sr.srshopid, sr.sritemid, sr.srdate sdate,'Rec' + convert(varchar(50), sr.srid) srno, sr.srid,                                       
 convert(numeric(18,3),sum(isnull(sr.srdedstock,0)))  as recAdd, 'Recovery Minus' type,-1 Mode, updatetime,         
 srCostPrice,srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,'' as 'From/To'         
from losstockrecovery sr                     
group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,                                         
 srCostPrice, srdepexrate, srconexrate having sum(isnull(sr.srdedstock,0)) >0                                        
                                     
union all                                        
                                        
--stockverification minus                                        
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,                                         
 convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty,'Verification Minus' type, -1 mode,        
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice        
 ,'' as 'From/To'                                          
from  losstockverificationheader, losstockverificationdetail         
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock                                        
 and svhCancelled=0 and  left(svhFutureVc, 1) <> 't'                     
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,                                         
 svdCostPrice, svhdepexrate , svhconexrate                                           
                                  
union all                                        
                                        
--Total stockverification minus                                        
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,                                         
 convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty,'Verification Minus' type, -1 mode,        
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice,        
 '' as 'From/To'     
from losstockverificationheader,losstockverificationdetail         
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock                                        
 and svhCancelled=0 and  left(svhFutureVc, 2) = 'tc'                     
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,                                         
 svdCostPrice, svhdepexrate , svhconexrate                                    
                                
union all                                        
                                        
--pos sales                                        
select poshShopID, posditemid, poshBilldate sdate, poshBillNo, poshbillid,                                         
 convert(numeric(18,3),sum(isnull(posdquantity,0))) cashsales,'Cash Sales' as type, -1 mode,updatetime,         
 posdCostPrice,posdCostPrice * poshdepexrate depCostPrice,posdCostPrice * poshExchangeRate ConCostPrice        
 ,'' as 'From/To'        
from losposdetail,losposheader                                         
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0                     
group by poshshopid, poshbillid, poshBillNo, poshbilldate, poshbillid, poshBillNo,                                         
 posditemid,updatetime, posdCostPrice, poshdepexrate, poshExchangeRate                                  
                 
union all                                        
                                        
--credit invoice                                        
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceNo, ihInvoiceid,                                          
 convert(numeric(18,3),sum(isnull(idquantity,0))) as creditsales, 'Credit Sales' Type,                                         
 -1 mode,updatetime, idCostPrice, idCostPrice * ihdepexrate depCostPrice,                                         
 idCostPrice * ihExchangeRate ConCostPrice,'' as 'From/To'          
from losinvoicedetail,losinvoiceheader                                        
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0 and ihType ='I'                     
group by ihshopid, ihinvoicedate, ihInvoiceid, ihInvoiceNo, iditemid,                          
 updatetime, idCostPrice, ihdepexrate, ihExchangeRate                                        
                                     
union all                                        
                                        
--exchange out                                        
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeno, sehexchangeid,                                          
 convert(numeric(18,3),sum(isnull(sedquantity,0)))  as exchangedout ,                                         
 'Exchange Out' Type, -1 mode,updatetime, sedCostPRice,                                        
 sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,'' as 'From/To'                                             
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID                                         
 and sedShopID=sehShopid and sedBillorExchange='E' and SEHCANCELLED=0                    
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,                                         
 sedCostPRice, sehdepexrate, sehExchangerate                                         
                                        
union all                                        
                                        
--special invoice return to shop                                        
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceNo, ihInvoiceid,                                          
 convert(numeric(18,3),-sum(isnull(reqqty,0)))   as SpecialReturn, 'Special Invoice Return' Type,                                         
 1 mode,updatetime, idCostPrice,                                         
 idCostPrice * ihdepexrate depCostPrice, idCostPrice * ihExchangerate ConCostPrice,'' as 'From/To'         
from losspecialinvoicedetail, losspecialinvoiceheader                                        
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1                                        
 and ihproforma=0 and ihTransFinished = 1                     
group by ihshopid, ihinvoicedate, ihInvoiceid,                                         
 ihInvoiceNo, iditemid, updatetime, idCostPrice, ihdepexrate, ihExchangerate                             
 -- transfinished added as stock is updated only after confirming                                        
                                        
union all                                        
                                        
 --COMMENTED AS MODIFICATIONS ON SERVICE IS GOING ON. TO BE REMOVED ONCE IT IS COMPLETED                                        
select serinvhShopid, repinvdpartsid, serinvhdate , serinvNo, serinvhid,                                          
 convert(numeric(18,3) , sum(repinvdqty)) , 'Parts Replaced' type,-1 as mode, serinvhupdatetime, repinvdcostprice,                                         
 repinvdCostPrice * seinvhdepexrate depCostPrice, repinvdCostPrice * serinvhcmpexrate ConCostPrice,'' as 'From/To'        
from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid                                          
 and serinvhshopid = repinvdshopid AND serinvhcancelled=0                                         
group by serinvhShopid,  serinvhdate , serinvhid , serinvNo ,  repinvdpartsid,                                         
 serinvhupdatetime, repinvdcostprice, seinvhdepexrate, serinvhcmpexrate                                        
                                        
union all                                        
                                         
--Re-Exporting                                        
select rehShopID, reditemid, rehExportDate sdate, rehExportNo, rehExportID,                                        
 convert(numeric(18,3),sum(isnull(redquantity,0)))  as creditsales, 'Re-Export' Type,                                         
 -1 mode, rehUpdatetime, redCostPrice,                                         
 redCostPrice * rehdepexrate depCostPrice, redCostPrice * rehExchangerate ConCostPrice,'' as 'From/To'        
from losexportdetail, losexportheader                                        
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0 and rehType='I'                     
group by rehShopID, rehExportDate, rehExportID, rehExportNo, redItemID,                                         
 rehUpdatetime, redCostPrice, rehdepexrate, rehExchangerate                                        
                                 
union all                                  
                                
--MerGing minus                                  
select lsdShopID, lsdItemID, lshDate, lshno, lshid,convert(numeric(18,3), sum(lsdqty)) as mergeded,                                   
 'Merging Deduct' as type, -1 as mode, lshUpdatetime,null,null,null,'' as 'From/To'                                  
from losMergeDetails md, losMergeHeader mh                                   
where md.lsdid = mh.lshid and md.lsdShopid = mh.lshShopId and lshCancelled=0                      
group by lsdShopID, lsdItemID, lshDate, lshid, lshno, lshUpdatetime                                  
Having Sum(lsdQty) <> 0                                   
                                  
union all                                  
                                
--MerGing Add                                  
select lsdShopID, lshItemID, lshDate, lshno, lshid,convert(numeric(18,3),sum(lsdqty)) as splitminus,                                   
 'Merging Add' as type, 1 as mode, lshUpdatetime,null,null,null,'' as 'From/To'                                  
from losMergeDetails md, losMergeHeader mh                                   
where md.lsdid = mh.lshid and md.lsdShopID = mh.lshShopid and lshCancelled = 0                       
group by lsdShopID, lshItemID, lshDate, lshid, lshno, lshUpdatetime                    
Having Sum(lsdQty) <> 0                         
                         
union all                                  
                                  
--Purchase Return                                  
select Ph.whshopid, Pd.wditemid, Ph.whdate sdate, Ph.whno, Ph.whid,                                   
 convert(numeric(18,3),sum(Pd.wdPurchaseReturnQty)) as PurchaseReturnqty, 'Purchase Return' TYpe, -1 mode,                                   
 updatetime, wdCostPrice,                                   
 wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'' as 'From/To'                                   
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd                                  
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid and Ph.whcancelled=0 and Ph.whtransfinished=1                     
group by Ph.whshopid, Ph.whDate, Ph.whid, Ph.whno, Pd.wditemid,updatetime, wdCostPrice,                                   
 whDepExrate, whConExrate                               
                              
union all                                        
                                       
--Warrenty Claim/Business promotion                                           
select wchShopID, wcditemid, wchdate sdate, wchNo, wchid,convert(numeric(18,3),sum(isnull(wcdQty,0))) BPWP,                                         
 'WC/BP' as type, -1 mode,wchupdatedtime, wcdCostPrice,wcdCostPrice * wchdepexrate depCostPrice,                                         
 wcdCostPrice * wchcomexrate ConCostPrice,'' as 'From/To'          
from losWarrentyClaimDetail,losWarrentyClaimHeader                                         
where wchID=wcdID and wchShopid=wcdshopid AND WCHCANCELLED=0                     
group by wchShopid, wchid, wchNo, wchdate, wchid, wchNo,                                         
 wcditemid,wchupdatedtime, wcdCostPrice, wchdepexrate, wchcomexrate                                       
                                       
union all                                      
                                      
-----Hire Purchase Invoice                                     
select hpqhShopid,hpqdItemId,hpqhQuotationDate sDate,hpqhQuotationNo,hpqhQuotationID,1 as Qty, 'Hire Purchase' Type,                                 
 -1 mode,hpqhUpdatetime,hpqdCostPrice,hpqdCostPrice*1 depCostPrice,hpqdCostPrice*1 ComCostPrice,'' as 'From/To'        
from loshpInvoiceDetail,losHpInvoiceHeader where hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and                                      
 hpqhCancel=0 and hpqhType='I'                     
group by hpqhShopid,hpqhQuotationDate,hpqhQuotationID,hpqhQuotationNo,hpqdItemId,hpqhUpdatetime,hpqdCostPrice                    
                    
union all                                     
                  
-- Food and Beverages Bill - added by Regin on 18-09-2010                  
SELECT Fb_kh_outletid, a.fb_ItemID, DATEADD(D, 0, DATEDIFF(D, 0, Fb_kh_kotdatetime)) sdate,Fb_kh_kotno, Fb_kh_kotid,         
 a.KotOrder,'FandB Bill' Type, -1 mode, Fb_kh_kotdatetime,fb_costprice, fb_costprice*h.fb_depexrate depCostPrice,         
 fb_costprice*h.fb_ExchangeRate conCostPrice,'' as 'From/To'                  
from fb_kotheader h                  
 inner join fb_alternate a on Fb_kh_kotid=fb_kotID                  
where Fb_kh_cancelled=0               
              
union all              
              
--InHouse Return                                       
SELECT IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,              
 convert(numeric(18,3),sum(IHRDReturnedqty)) as IHRDReturnedqty,'In-House Return' Type,1 mode,updatetime,              
 IHRDcostprice,(IHRHdepexrate*IHRDcostprice) DepCostPrice,(IHRHconexrate*IHRDcostprice)ConCostPrice        
 ,'' as 'From/To'              
FROM LOs_InHouseCons_ReturnHeader rh                
INNER JOIN  LOs_InHouseCons_ReturnDetail rd               
on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND IHRHConfirmed=1               
AND (IHRDRetrnOrExch='R' OR IHRDRetrnOrExch='B' OR IHRDRetrnOrExch IS NULL) AND IHRDReturnedqty<>0            
group by IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,updatetime,                                      
IHRDcostprice,IHRHdepexrate,IHRHconexrate                
              
UNION ALL              
              
--InHouse Exchanged In                            
SELECT IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,              
 convert(numeric(18,3),sum(IHRDArrivedQty)) as IHRDExchgdqty,'In-House Exchnaged In' Type,-1 mode,updatetime,              
 IHRDcostprice,(IHRHdepexrate*IHRDcostprice) DepCostPrice,(IHRHconexrate*IHRDcostprice)ConCostPrice,'' as 'From/To'              
FROM LOs_InHouseCons_ReturnHeader rh                
 INNER JOIN  LOs_InHouseCons_ReturnDetail rd on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND         
 IHRHConfirmed=1 AND IHRDRetrnOrExch='E' AND IHRDArrivedQty<>0              
group by IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,updatetime,IHRDcostprice,IHRHdepexrate,IHRHconexrate 
GO


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_030
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


GO

/****** Object:  View [dbo].[vwShopBincardAudit_new]    Script Date: 03/27/2012 11:55:49 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBincardAudit_new]'))
DROP VIEW [dbo].[vwShopBincardAudit_new]
GO


/****** Object:  View [dbo].[vwShopBincardAudit_new]    Script Date: 03/27/2012 11:55:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--sp_helptext vwshopbincardaudit
   
-- Modified By   : Benzigar 23092008                        
-- Modified Date : 23092008                        
-- Comment       : Added Business Promotion/Warrenty claim              
-- =====================================              
-- Upgraded By : Regin T.              
-- Upgraded On : 22-07-2010              
-- Upgrade     : An outer Group By clause was used to change               
--   the position of TransId and TransNo fields.              
--   This Group By clause casued delay. So I removed it, and               
--   changed the position of fields in all union all parts.              
--   Old position: TransId, TransNo              
--   New position: TransNo, TransId              
-- =====================================              
-- Upgraded By : Regin T.            
-- Upgraded On : 18-09-2010              
-- Upgrade     : Added FandB Bill            
-- =====================================            
-- Upgraded By : NIDHEESH P.V.            
-- Upgraded On : 09-02-2011              
-- Upgrade     : Added In-House Return           
-- =====================================       
--------------------------------------------------------------------------------  
-- Modified by          : MANUNADH.U ON : 11/05/2011  
-- Comments             : Added the column From/To for Bincard Audit report                
--------------------------------------------------------------------------------       
 --------------------------------------------------------------------------------  
-- Modified by          : AADYAKUMAR.D.V ON : 31/05/2011  
-- Comments             : Bug fixed in transfer out
--------------------------------------------------------------------------------       
-- Referenc No  : Ref-No1          
-- Modified by	: MANUNADH.U      
-- Modified on	: 26/03/2012              
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1
-- ------------------------------------------------------------------------------

                       
create VIEW [dbo].[vwShopBincardAudit_new] AS     
--arrival from godown     
select h.gahshopid ShopId, d.gaditemid ItemId, h.gaharrivaldate sDate,h.gaharrivalno TransNo,h.gaharrivalid TransId,  
 convert(numeric(18,3),isnull(sum(d.gadItemGoodQuantityArrived),0)) TransQty,'Arrival From Godown' [Type],   
 1 Mode, UpdateTime, gadCostprice CostPrice,gadCostPrice * gahdepexrate DepCostPrice,   
 gadCostPrice * gahconexrate ConCostPrice,  
 --(case when g.GodownName IS null then 'HQ' else g.GodownName end  + '/' + s.ShopName)  as 'From/To'   
 (case when g.GodownName IS null then 'HQ' else g.GodownName end  )  as 'From/To'                
from losgoodsarrivaltoshopheader h  
 left outer join aGodown g on g.GodownID=h.gahDespatchedGodownID  
 left outer join ashops s on s.ShopID=h.gahShopid,losgoodsarrivaltoshopdetail d  
where h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and h.gahtransfinished=1       
 AND gaharrivaldate >='20100101' and gaharrivaldate<='20110131' --and h.gahshopid=5  
group by  h.gahshopid, h.gaharrivaldate, h.gaharrivalid,gaharrivalno, d.gaditemid,updatetime, gadCostprice,   
 gahdepexrate, gahconexrate,g.GodownName,s.ShopName                                        
                                  
----GOODS RETURN TO SHOPS FROM CREDIT INVOICES                                  
union all                                  
                                  
select grn.grnhShopid, grd.GRNDItemID, GrnhGoodsreturnnoteDate sdate,GrnhGoodsreturnnoteNO transno,   
 GrnhGoodsreturnnoteID transid, convert(numeric(18,3),isnull(GRNDQuantity,0)) transqty,'Goods Return',1 as mode,  
 updatetime, grncostprice,grncostprice * grnhdepexrate depCostPrice, grncostprice * grnhExchangeRate ConCostPrice,  
 '' as 'From/To'  
from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd                                  
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid = grd.GRNDShopid and GrnhCancel=0   
 and GRNDDamaged=0  
                                  
union all                                  
                                  
--transfer in                                  
select h.tihshopid shopid,  d.tiditemid itemid, h.tihdate sdate, h.tihno, h.tihid,                                   
 convert(numeric(18,3),sum(d.TIDrecievedgoodqty)) as TinQty, 'Transfer In' TYpe, 1 mode,updatetime, tidCostPrice,   
 tidCostPrice * tihdepexrate depCostPrice, tidCostPrice * tihconexrate ConCostPrice ,s.ShopName as 'From/To'                                  
from lostransferinheader h  
 left outer join ashops s on s.ShopID=h.TIHfromshopID,lostransferindetail d   
where h.tihid=d.tidid and h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1              
group by h.tihshopid, h.tihdate,  h.tihid, h.tihno, d.tiditemid ,updatetime, tidCostPrice ,                                   
 tihdepexrate, tihconexrate,s.ShopName                                  
                                  
union all     
                                  
--recovery add                                  
select sr.srshopid, sr.sritemid, sr.srdate sdate, 'Rec' + convert(varchar(50), sr.srid) srno, sr.srid,                                                       
 convert(numeric(18,3),isnull(sum(sr.sraddstock),0))  as recAdd, 'Recovery Plus' Type,1 Mode,updatetime,   
 srCostPrice,srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,'' as 'From/To'    
from losstockrecovery sr               
group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,srCostPrice, srdepexrate, srconexrate                                   
having isnull(sum(sr.sraddstock),0) >0  
                                  
union all                                  
                                  
--stock verification add                                  
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,  
 convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,'Verification Plus' Type, 1 mode,  
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice  
 ,'' as 'From/To'                                    
from  losstockverificationheader, losstockverificationdetail   
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and    
 left(svhFutureVc, 1) <> 't'                 
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,svdCostPrice, svhdepexrate, svhconexrate                                  
                            
union all                                  
                                  
--TOTAL stock verification add                                  
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,  
 convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,'Verification Plus' Type, 1 mode,  
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice   
 ,'' as 'From/To'                                   
from  losstockverificationheader, losstockverificationdetail   
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock and svhCancelled=0 and    
 left(svhFutureVc, 2) = 'tc'                
group by svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,svdCostPrice, svhdepexrate, svhconexrate                                  
                                        
union all                                  
                                  
--exchange in                                  
                                  
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeno, sehexchangeid,                
 convert(numeric(18,3),sum(isnull(sedExchangeQty,0)))  as exchangedin, 'Exchanged In' Type,1 mode,updatetime,   
 sedCostPrice,sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,'' as 'From/To'       
from losposexchangeheader, losposexchangedetail   
where sedExchangeid=sehExchangeID and sedShopID=sehShopid and sedBillorExchange='B' and SEHCANCELLED=0                                  
 and isnull(sedExchangeQty,0) >0                                  
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,                                   
 sedCostPrice, sehDepExrate, sehExchangerate                                    
                                  
union all                                  
                                  
--local purchase                                
select lphShopid, lpditemid, lphbilldate, lphBillNo, lphBillid,                                    
	convert(numeric(18,3),sum(isnull(lpdItemQuantity,0))) localpurchase,'Local Purchase' Type, 1 mode,updatetime,   
	(lpdItemUnitPrice/ lpdItemQuantity),(lpdItemUnitPrice/ lpdItemQuantity) * lphdepexrate depCostPrice,                                   
	(lpdItemUnitPrice/ lpdItemQuantity)* lphExchangerate ConCostPrice ,'' as 'From/To'                                      
from loslocalpurchasedetail, loslocalpurchaseheader   
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphConfirmed=1 --<<Ref-No1>>               
group by lphshopid, lphBillid, lphBillNo,lphbilldate, lpditemid,updatetime, lpdItemUnitPrice, lpdItemQuantity,   
	lphdepexrate,lphExchangerate                 
                                  
union all                                  
                                  
--write off                                  
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whno, wh.whid,                                   
 convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty, 'Write off' TYpe, -1 mode,updatetime, wdCostPrice,                                   
 wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'' as 'From/To'                                   
from loswriteoffheader wh, loswriteoffdetail wd                                  
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0               
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,                                   
 whDepExrate, whConExrate                                  
                                  
union all                                  
                                  
--Despatch                                  
select dd.dgdshopid, dd.dgditemid, dh.dghDate sdate, dh.dghNo, dh.dghid,                                   
 convert(numeric(18,3),sum(dd.dgddespatchedgoodqty)) as despatchqty,'Despatch To Godown' TYpe, -1 mode,updatetime,  
 dgdCostPrice,dgdCostPrice * dghdepexrate depCostPrice, dgdCostPrice * dghConExrate ConCostPrice  
 ,g.GodownName  as 'From/To'                                                
from mesdespatchtogodownheader dh  
 left outer join aGodown g on g.GodownID=dh.dghGodownID,mesdespatchtogodowndetail dd                                   
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0                     
 and dghtransfinished = 1 -- for the concept of stock updation after transaction finish                                   
group by dd.dgdshopid, dh.dghdate, dh.dghid, dh.dghNo,dd.dgditemid,updatetime,                                   
 dgdCostPrice, dghdepexrate, dghconexrate,g.GodownName                                  
                                 
union all                                  
                                  
--Transferout                                  
select todshopid, toditemid, tohDate sdate, tohno, tohid,                                   
convert(numeric(18,3),sum(todissuedgoodqty)) as ToutQty ,
'Transfer Out' Type,-1 mode,updatetime, todCostPrice,                                   
todCostPrice * tohdepexrate depCostPrice, todCostPrice * tohConExrate ConCostPrice,s.ShopName as 'From/To'
from mestransferoutdetail inner join mestransferoutheader h 
on tohid=todid and Tohshopid=todshopid and tohcancelled=0 and tohtransfinished = 1 inner join 
ashops s on s.ShopID=h.TOHtoShopid --inner join lostransferindetail on TODitemid=TIDitemID 
where TOHShopid=5 and TODitemid=8626 
group by todissuedgoodqty,tohid,todshopid, tohdate, tohid, tohno, todItemid,updatetime, todCostPrice,                                   
tohdepexrate, tohConExrate,s.ShopName  
                              
                                  
union all                                  
                                  
--recovery minus                                  
select sr.srshopid, sr.sritemid, sr.srdate sdate,'Rec' + convert(varchar(50), sr.srid) srno, sr.srid,                                 
 convert(numeric(18,3),sum(isnull(sr.srdedstock,0)))  as recAdd, 'Recovery Minus' type,-1 Mode, updatetime,   
 srCostPrice,srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,'' as 'From/To'   
from losstockrecovery sr               
group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,                                   
 srCostPrice, srdepexrate, srconexrate having sum(isnull(sr.srdedstock,0)) >0                                  
                               
union all                                  
                                  
--stockverification minus                                  
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,                                   
 convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty,'Verification Minus' type, -1 mode,  
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice  
 ,'' as 'From/To'                                    
from  losstockverificationheader, losstockverificationdetail   
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock                                  
 and svhCancelled=0 and  left(svhFutureVc, 1) <> 't'               
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,                                   
 svdCostPrice, svhdepexrate , svhconexrate                                     
                            
union all                                  
                                  
--Total stockverification minus                                  
select svdshopid, svdItemid, svhDate sdate, svhno, svhid,                                   
 convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty,'Verification Minus' type, -1 mode,  
 updatetime, svdCostPrice,svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice,  
 '' as 'From/To'                                    
from losstockverificationheader,losstockverificationdetail   
where svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock                                  
 and svhCancelled=0 and  left(svhFutureVc, 2) = 'tc'               
group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,                                   
 svdCostPrice, svhdepexrate , svhconexrate                              
                          
union all                                  
                                  
--pos sales                                  
select poshShopID, posditemid, poshBilldate sdate, poshBillNo, poshbillid,                                   
 convert(numeric(18,3),sum(isnull(posdquantity,0))) cashsales,'Cash Sales' as type, -1 mode,updatetime,   
 posdCostPrice,posdCostPrice * poshdepexrate depCostPrice,posdCostPrice * poshExchangeRate ConCostPrice  
 ,'' as 'From/To'  
from losposdetail,losposheader                                   
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0               
group by poshshopid, poshbillid, poshBillNo, poshbilldate, poshbillid, poshBillNo,                                   
 posditemid,updatetime, posdCostPrice, poshdepexrate, poshExchangeRate                            
                                  
union all                                  
                                  
--credit invoice                                  
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceNo, ihInvoiceid,                                    
 convert(numeric(18,3),sum(isnull(idquantity,0))) as creditsales, 'Credit Sales' Type,                                   
 -1 mode,updatetime, idCostPrice, idCostPrice * ihdepexrate depCostPrice,                                   
 idCostPrice * ihExchangeRate ConCostPrice,'' as 'From/To'    
from losinvoicedetail,losinvoiceheader                                  
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0 and ihType ='I'               
group by ihshopid, ihinvoicedate, ihInvoiceid, ihInvoiceNo, iditemid,                    
 updatetime, idCostPrice, ihdepexrate, ihExchangeRate                                  
                               
union all                                  
                                  
--exchange out                                  
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeno, sehexchangeid,                                    
 convert(numeric(18,3),sum(isnull(sedquantity,0)))  as exchangedout ,                                   
 'Exchange Out' Type, -1 mode,updatetime, sedCostPRice,                                  
 sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,'' as 'From/To'                                       
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID                                   
 and sedShopID=sehShopid and sedBillorExchange='E' and SEHCANCELLED=0              
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,                                   
 sedCostPRice, sehdepexrate, sehExchangerate                                   
                                  
union all                                  
                                  
--special invoice return to shop                                  
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceNo, ihInvoiceid,                                    
 convert(numeric(18,3),-sum(isnull(reqqty,0)))   as SpecialReturn, 'Special Invoice Return' Type,                                   
 1 mode,updatetime, idCostPrice,                                   
 idCostPrice * ihdepexrate depCostPrice, idCostPrice * ihExchangerate ConCostPrice,'' as 'From/To'   
from losspecialinvoicedetail, losspecialinvoiceheader                                  
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1                                  
 and ihproforma=0 and ihTransFinished = 1               
group by ihshopid, ihinvoicedate, ihInvoiceid,                                   
 ihInvoiceNo, iditemid, updatetime, idCostPrice, ihdepexrate, ihExchangerate                       
 -- transfinished added as stock is updated only after confirming                                  
                                  
union all                                  
                                  
 --COMMENTED AS MODIFICATIONS ON SERVICE IS GOING ON. TO BE REMOVED ONCE IT IS COMPLETED                                  
select serinvhShopid, repinvdpartsid, serinvhdate , serinvNo, serinvhid,                                    
 convert(numeric(18,3) , sum(repinvdqty)) , 'Parts Replaced' type,-1 as mode, serinvhupdatetime, repinvdcostprice,                                   
 repinvdCostPrice * seinvhdepexrate depCostPrice, repinvdCostPrice * serinvhcmpexrate ConCostPrice,'' as 'From/To'  
from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid                                    
 and serinvhshopid = repinvdshopid AND serinvhcancelled=0                                   
group by serinvhShopid,  serinvhdate , serinvhid , serinvNo ,  repinvdpartsid,                                   
 serinvhupdatetime, repinvdcostprice, seinvhdepexrate, serinvhcmpexrate                                  
                                  
union all                                  
                                   
--Re-Exporting                                  
select rehShopID, reditemid, rehExportDate sdate, rehExportNo, rehExportID,                                  
 convert(numeric(18,3),sum(isnull(redquantity,0)))  as creditsales, 'Re-Export' Type,                                   
 -1 mode, rehUpdatetime, redCostPrice,                                   
 redCostPrice * rehdepexrate depCostPrice, redCostPrice * rehExchangerate ConCostPrice,'' as 'From/To'  
from losexportdetail, losexportheader                                  
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0 and rehType='I'               
group by rehShopID, rehExportDate, rehExportID, rehExportNo, redItemID,                                   
 rehUpdatetime, redCostPrice, rehdepexrate, rehExchangerate                                  
                           
union all                            
                          
--MerGing minus                            
select lsdShopID, lsdItemID, lshDate, lshno, lshid,convert(numeric(18,3), sum(lsdqty)) as mergeded,                             
 'Merging Deduct' as type, -1 as mode, lshUpdatetime,null,null,null,'' as 'From/To'                            
from losMergeDetails md, losMergeHeader mh                             
where md.lsdid = mh.lshid and md.lsdShopid = mh.lshShopId and lshCancelled=0                
group by lsdShopID, lsdItemID, lshDate, lshid, lshno, lshUpdatetime                            
Having Sum(lsdQty) <> 0                             
                            
union all                            
                          
--MerGing Add                            
select lsdShopID, lshItemID, lshDate, lshno, lshid,convert(numeric(18,3),sum(lsdqty)) as splitminus,                             
 'Merging Add' as type, 1 as mode, lshUpdatetime,null,null,null,'' as 'From/To'                            
from losMergeDetails md, losMergeHeader mh                             
where md.lsdid = mh.lshid and md.lsdShopID = mh.lshShopid and lshCancelled = 0                 
group by lsdShopID, lshItemID, lshDate, lshid, lshno, lshUpdatetime                            
Having Sum(lsdQty) <> 0                   
                   
union all                            
                            
--Purchase Return                            
select Ph.whshopid, Pd.wditemid, Ph.whdate sdate, Ph.whno, Ph.whid,                             
 convert(numeric(18,3),sum(Pd.wdPurchaseReturnQty)) as PurchaseReturnqty, 'Purchase Return' TYpe, -1 mode,                             
 updatetime, wdCostPrice,                             
 wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,'' as 'From/To'                             
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd                            
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid and Ph.whcancelled=0 and Ph.whtransfinished=1               
group by Ph.whshopid, Ph.whDate, Ph.whid, Ph.whno, Pd.wditemid,updatetime, wdCostPrice,                             
 whDepExrate, whConExrate                         
                        
union all                                  
                                 
--Warrenty Claim/Business promotion                                     
select wchShopID, wcditemid, wchdate sdate, wchNo, wchid,convert(numeric(18,3),sum(isnull(wcdQty,0))) BPWP,                                   
 'WC/BP' as type, -1 mode,wchupdatedtime, wcdCostPrice,wcdCostPrice * wchdepexrate depCostPrice,                                   
 wcdCostPrice * wchcomexrate ConCostPrice,'' as 'From/To'    
from losWarrentyClaimDetail,losWarrentyClaimHeader                                   
where wchID=wcdID and wchShopid=wcdshopid AND WCHCANCELLED=0               
group by wchShopid, wchid, wchNo, wchdate, wchid, wchNo,                                   
 wcditemid,wchupdatedtime, wcdCostPrice, wchdepexrate, wchcomexrate                                 
                                 
union all                                
                                
-----Hire Purchase Invoice                               
select hpqhShopid,hpqdItemId,hpqhQuotationDate sDate,hpqhQuotationNo,hpqhQuotationID,1 as Qty, 'Hire Purchase' Type,                           
 -1 mode,hpqhUpdatetime,hpqdCostPrice,hpqdCostPrice*1 depCostPrice,hpqdCostPrice*1 ComCostPrice,'' as 'From/To'  
from loshpInvoiceDetail,losHpInvoiceHeader where hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and                                
 hpqhCancel=0 and hpqhType='I'               
group by hpqhShopid,hpqhQuotationDate,hpqhQuotationID,hpqhQuotationNo,hpqdItemId,hpqhUpdatetime,hpqdCostPrice              
              
union all                               
            
-- Food and Beverages Bill - added by Regin on 18-09-2010            
SELECT Fb_kh_outletid, a.fb_ItemID, DATEADD(D, 0, DATEDIFF(D, 0, Fb_kh_kotdatetime)) sdate,Fb_kh_kotno, Fb_kh_kotid,   
 a.KotOrder,'FandB Bill' Type, -1 mode, Fb_kh_kotdatetime,fb_costprice, fb_costprice*h.fb_depexrate depCostPrice,   
 fb_costprice*h.fb_ExchangeRate conCostPrice,'' as 'From/To'            
from fb_kotheader h            
 inner join fb_alternate a on Fb_kh_kotid=fb_kotID            
where Fb_kh_cancelled=0         
        
union all        
        
--InHouse Return                                 
SELECT IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,        
 convert(numeric(18,3),sum(IHRDReturnedqty)) as IHRDReturnedqty,'In-House Return' Type,1 mode,updatetime,        
 IHRDcostprice,(IHRHdepexrate*IHRDcostprice) DepCostPrice,(IHRHconexrate*IHRDcostprice)ConCostPrice  
 ,'' as 'From/To'        
FROM LOs_InHouseCons_ReturnHeader rh          
INNER JOIN  LOs_InHouseCons_ReturnDetail rd         
on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND IHRHConfirmed=1         
AND (IHRDRetrnOrExch='R' OR IHRDRetrnOrExch='B' OR IHRDRetrnOrExch IS NULL) AND IHRDReturnedqty<>0        
group by IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,updatetime,                                
IHRDcostprice,IHRHdepexrate,IHRHconexrate          
        
UNION ALL        
        
--InHouse Exchanged In                      
SELECT IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,        
 convert(numeric(18,3),sum(IHRDArrivedQty)) as IHRDExchgdqty,'In-House Exchnaged In' Type,-1 mode,updatetime,        
 IHRDcostprice,(IHRHdepexrate*IHRDcostprice) DepCostPrice,(IHRHconexrate*IHRDcostprice)ConCostPrice,'' as 'From/To'        
FROM LOs_InHouseCons_ReturnHeader rh          
 INNER JOIN  LOs_InHouseCons_ReturnDetail rd on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND   
 IHRHConfirmed=1 AND IHRDRetrnOrExch='E' AND IHRDArrivedQty<>0        
group by IHRHShopID,IHRDItemID,IHRHDate,IHRHNo,IHRHID,updatetime,IHRDcostprice,IHRHdepexrate,IHRHconexrate          
        
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_030
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

/****** Object:  View [dbo].[vwShopBinCardAudit_Pos]    Script Date: 03/27/2012 14:21:04 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBinCardAudit_Pos]'))
DROP VIEW [dbo].[vwShopBinCardAudit_Pos]
GO


/****** Object:  View [dbo].[vwShopBinCardAudit_Pos]    Script Date: 03/27/2012 14:21:05 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--Created By : Benzigar S D    
--Created On : 20/01/2009       
--Comment    : To Speed up POS   
-----------------------------------------  
--MODIFIED BY : NIDHEESH PV  
--MODIFIED ON :09/02/2011  
--cOMMENTS : ADDED INHOUSE RETURN  
--------------------------------------------------------------------------------      
--Modified by          : Nidheesh P V  
--Modified on          : 6/07/2011          
--Comments             : Added In-House Consumption part seperately.  
--Modified Area        : All Interfaces where stock effects  
--Referenc No          : Ref-No1      
--------------------------------------------------------------------------------        
-- Referenc No  : Ref-No2
-- Modified by	: MANUNADH.U      
-- Modified on	: 26/03/2012              
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1
-------------------------------------------------------------------------------- 

CREATE  VIEW [dbo].[vwShopBinCardAudit_Pos] AS         
select shopid, itemid    
from         
--arrival from godown        
(select h.gahshopid shopid, d.gaditemid itemid from         
losgoodsarrivaltoshopheader h, losgoodsarrivaltoshopdetail d where         
h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and         
h.gahtransfinished=1 group by  h.gahshopid, h.gaharrivaldate, h.gaharrivalid,         
gaharrivalno, d.gaditemid,updatetime, gadCostprice, gahdepexrate, gahconexrate        
        
--GOODS RETURN TO SHOPS FROM CREDIT INVOICES        
union all        
        
select grn.grnhShopid, grd.GRNDItemID from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd        
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid =         
grd.GRNDShopid and GrnhCancel=0 and GRNDDamaged=0         
        
union all        
        
--transfer in        
select h.tihshopid shopid,  d.tiditemid itemid        
 from lostransferinheader h, lostransferindetail d where h.tihid=d.tidid and         
h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1         
group by h.tihshopid, h.tihdate,  h.tihid, h.tihno, d.tiditemid ,updatetime, tidCostPrice ,         
tihdepexrate, tihconexrate        
        
union all        
        
--recovery add        
select sr.srshopid, sr.sritemid from         
losstockrecovery sr group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,         
srCostPrice, srdepexrate, srconexrate         
having isnull(sum(sr.sraddstock),0) >0        
        
        
union all        
        
--stock verification add        
select svdshopid, svdItemid          
from  losstockverificationheader, losstockverificationdetail where        
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock        
and svhCancelled=0 group by   svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,         
svdCostPrice, svhdepexrate, svhconexrate        
        
union all        
        
--exchange in        
        
select sehShopID, seditemid from         
losposexchangeheader, losposexchangedetail where sedExchangeid=sehExchangeID         
and sedShopID=sehShopid and sedBillorExchange='B' and SEHCANCELLED=0        
and isnull(sedExchangeQty,0) >0        
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,         
sedCostPrice, sehDepExrate, sehExchangerate          
        
union all        
        
--local purchase        
select lphShopid, lpditemid          
from loslocalpurchasedetail, loslocalpurchaseheader 
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphConfirmed=1--<<Ref-No2>> 
group by lphshopid, lphBillid, lphBillNo,lphbilldate, lpditemid,updatetime, lpdItemUnitPrice, lpdItemQuantity, 
	lphdepexrate,lphExchangerate        
        
union all        
        
--write off        
select wh.whshopid, wd.wditemid         
from loswriteoffheader wh, loswriteoffdetail wd        
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and whtype<>'I' --Ref-No1  
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,         
whDepExrate, whConExrate        
        
union all   
     
--InHouse Consumption   --Ref-No1       
select wh.whshopid, wd.wditemid         
from loswriteoffheader wh, loswriteoffdetail wd        
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and whtype='I' and whVerified=1 
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,         
whDepExrate, whConExrate        
        
union all        

--Deapatch        
select dd.dgdshopid, dd.dgditemid         
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd         
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0         
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish         
group by dd.dgdshopid, dh.dghdate, dh.dghid, dh.dghNo,dd.dgditemid,updatetime,         
dgdCostPrice, dghdepexrate, dghconexrate        
        
union all        
        
--Transferout        
select todshopid, toditemid        
 from mestransferoutheader , mestransferoutdetail  where        
tohid=todid and Tohshopid=todshopid and tohcancelled=0        
and tohtransfinished = 1 -- for the concept of stock updation after transaction finish         
group by todshopid, tohdate, tohid, tohno, todItemid,updatetime, todCostPrice,         
tohdepexrate, tohConExrate        
        
union all        
        
--recovery minus        
select sr.srshopid, sr.sritemid from         
losstockrecovery sr group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,         
srCostPrice, srdepexrate, srconexrate having sum(isnull(sr.srdedstock,0)) >0        
        
union all        
        
--stockverification minus        
select svdshopid, svdItemid      
from  losstockverificationheader, losstockverificationdetail where        
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock        
and svhCancelled=0 group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,         
svdCostPrice, svhdepexrate , svhconexrate         
  union all        
        
--pos sales        
select poshShopID, posditemid from losposdetail,losposheader         
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0 group by        
poshshopid, poshbillid, poshBillNo, poshbilldate, poshbillid, poshBillNo,         
posditemid,updatetime, posdCostPrice, poshdepexrate, poshExchangeRate        
        
union all        
        
--credit invoice        
select IhShopid, iditemid  from losinvoicedetail,losinvoiceheader        
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0        
and ihType ='I' group by ihshopid, ihinvoicedate, ihInvoiceid, ihInvoiceNo, iditemid,         
updatetime, idCostPrice, ihdepexrate, ihExchangeRate        
        
union all        
        
--exchange out        
select sehShopID, seditemid           
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID         
and sedShopID=sehShopid and sedBillorExchange='E' and SEHCANCELLED=0        
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,         
sedCostPRice, sehdepexrate, sehExchangerate         
        
union all        
        
--special invoice return to shop        
select IhShopid, iditemid     
from losspecialinvoicedetail, losspecialinvoiceheader        
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1        
and ihproforma=0 and ihTransFinished = 1 group by ihshopid, ihinvoicedate, ihInvoiceid,         
ihInvoiceNo, iditemid, updatetime, idCostPrice, ihdepexrate, ihExchangerate        
 -- transfinished added as stock is updated only after confirming        
        
union all        
        
 --COMMENTED AS MODIFICATIONS ON SERVICE IS GOING ON. TO BE REMOVED ONCE IT IS COMPLETED        
  select serinvhShopid, repinvdpartsid       
  from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid          
  and serinvhshopid = repinvdshopid AND serinvhcancelled=0         
  group by serinvhShopid,  serinvhdate , serinvhid , serinvNo ,  repinvdpartsid,         
 serinvhupdatetime, repinvdcostprice, seinvhdepexrate, serinvhcmpexrate        
        
  union all        
         
--Re-Exporting        
select rehShopID, reditemid         
from losexportdetail, losexportheader        
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0        
and rehType='I' group by rehShopID, rehExportDate, rehExportID, rehExportNo, redItemID,         
rehUpdatetime, redCostPrice, rehdepexrate, rehExchangerate  
  
UNION ALL  
  
--InHouse Return                           
SELECT IHRHShopID,IHRDItemID  
FROM LOs_InHouseCons_ReturnHeader rh    
INNER JOIN  LOs_InHouseCons_ReturnDetail rd   
on IHRHShopID=IHRDShopID and IHRHID=IHRDID AND IHRHCancelled=0 AND IHRHConfirmed=1  
group by IHRHShopID,IHRHID,IHRDItemID                       
                     
  
)        
 shopbin        
    
-------------------------------------------------------------------------------------------    
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_030
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

GO

/****** Object:  View [dbo].[vwShopBinCardAuditCustWise]    Script Date: 03/27/2012 14:25:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwShopBinCardAuditCustWise]'))
DROP VIEW [dbo].[vwShopBinCardAuditCustWise]
GO


/****** Object:  View [dbo].[vwShopBinCardAuditCustWise]    Script Date: 03/27/2012 14:25:08 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

----Created By   : Prasanth joseph        
----Created on   : 05-05-2008        
----Created for  : To get Bincard Audit Report Accoding to Customer    
---------------------------------------------------------------------------------------------------  
----Modified By  : Benzigar S D  
----Modified On  : 16-09-2009  
----Comment      : Modified sellingpriceperunit in POS and Credit Invoice Part      
--------------------------------------------------------------------------------      
--Modified by          : Nidheesh P V  
--Modified on          : 6/07/2011          
--Comments             : Added In-House Consumption part seperately.  
--Modified Area        : All Interfaces where stock effects  
--Referenc No          : Ref-No1      
-------------------------------------------------------------------------------- 
-- Referenc No  : Ref-No2          
-- Modified by	: MANUNADH.U      
-- Modified on	: 26/03/2012              
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1
-- -----------------------------------------------------------------------------
             
CREATE  VIEW [dbo].[vwShopBinCardAuditCustWise] AS            
            
select shopid, itemid, sdate , Transno, TransID ,Transqty, Type, mode,updatetime, Costprice,           
DepCostprice,ConCostprice,CustomerName,SellingPrice,sellingperUnit,Margin,CustID            
from             
--arrival from godown            
(select h.gahshopid shopid, d.gaditemid itemid, h.gaharrivaldate sdate,             
h.gaharrivalid Transid, h.gaharrivalno Transno,             
convert(numeric(18,3),isnull(sum(d.gadItemGoodQuantityArrived),0)) TransQty,             
'Arrival From Godown' Type, 1 mode,updatetime,gadCostprice CostPrice,             
gadCostPrice * gahdepexrate depCostPrice, gadCostPrice * gahconexrate ConCostPrice,'' CustomerName ,0 SellingPrice ,0 sellingperUnit,0 Margin,'' CustID from             
losgoodsarrivaltoshopheader h, losgoodsarrivaltoshopdetail d where             
h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and             
h.gahtransfinished=1 group by  h.gahshopid, h.gaharrivaldate, h.gaharrivalid,             
gaharrivalno, d.gaditemid,updatetime, gadCostprice, gahdepexrate, gahconexrate            
            
--GOODS RETURN TO SHOPS FROM CREDIT INVOICES            
union all            
            
select grn.grnhShopid, grd.GRNDItemID, GrnhGoodsreturnnoteDate sdate,            
GrnhGoodsreturnnoteID transid, GrnhGoodsreturnnoteNO transno, convert(numeric(18,3),isnull(GRNDQuantity,0)) transqty,            
'Goods Return',1 as mode,updatetime, grncostprice,             
grncostprice * grnhdepexrate depCostPrice, grncostprice * grnhExchangeRate ConCostPrice,'' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,grnhCustomerID CustID from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd            
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid =             
grd.GRNDShopid and GrnhCancel=0 and GRNDDamaged=0             
            
union all            
            
--transfer in            
select h.tihshopid shopid,  d.tiditemid itemid, h.tihdate sdate, h.tihid, h.tihno,            
convert(numeric(18,3),sum(d.TIDrecievedgoodqty)) as TinQty, 'Transfer In' TYpe, 1 mode,             
updatetime, tidCostPrice, tidCostPrice * tihdepexrate depCostPrice, tidCostPrice * tihconexrate ConCostPrice ,        
'' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'' CustID             
 from lostransferinheader h, lostransferindetail d where h.tihid=d.tidid and             
h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1             
group by h.tihshopid, h.tihdate,  h.tihid, h.tihno, d.tiditemid ,updatetime, tidCostPrice ,             
tihdepexrate, tihconexrate            
            
union all            
            
--recovery add            
select sr.srshopid, sr.sritemid, sr.srdate sdate, sr.srid,             
'Rec' + convert(varchar(50), sr.srid) srno,            
convert(numeric(18,3),isnull(sum(sr.sraddstock),0))  as recAdd, 'Recovery Plus' Type,             
1 Mode,updatetime, srCostPrice,             
srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice        
,'' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'' CustID  from             
losstockrecovery sr group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,             
srCostPrice, srdepexrate, srconexrate             
having isnull(sum(sr.sraddstock),0) >0            
            
            
union all            
            
--stock verification add            
select svdshopid, svdItemid, svhDate sdate, svhid, svhno,            
convert(numeric(18,3),sum(svdVerifiedStock-svdAvailStock)) as svAddQty,             
'Verification Plus' Type, 1 mode,updatetime, svdCostPrice,             
svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice,        
'' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'' CustID             
from  losstockverificationheader, losstockverificationdetail where            
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock            
and svhCancelled=0 group by   svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,             
svdCostPrice, svhdepexrate, svhconexrate            
            
union all            
            
--exchange in            
            
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeid, sehexchangeno,             
convert(numeric(18,3),sum(isnull(sedExchangeQty,0)))  as exchangedin, 'Exchanged In' Type,             
1 mode,updatetime, sedCostPrice,             
sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,        
'' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'' CustID    from             
losposexchangeheader, losposexchangedetail where sedExchangeid=sehExchangeID             
and sedShopID=sehShopid and sedBillorExchange='B' and SEHCANCELLED=0            
and isnull(sedExchangeQty,0) >0            
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,             
sedCostPrice, sehDepExrate, sehExchangerate              
            
union all            
            
--local purchase            
select lphShopid, lpditemid, lphbilldate, lphBillid, lphBillNo,             
	convert(numeric(18,3),sum(isnull(lpdItemQuantity,0))) localpurchase,'Local Purchase' Type, 1 mode,updatetime, 
	(lpdItemUnitPrice/ lpdItemQuantity),(lpdItemUnitPrice/ lpdItemQuantity) * lphdepexrate depCostPrice,             
	(lpdItemUnitPrice/ lpdItemQuantity)* lphExchangerate ConCostPrice,'' CustomerName,0 SellingPrice,0 sellingperUnit,
	0 Margin,'' CustID              
from loslocalpurchasedetail, loslocalpurchaseheader 
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphconfirmed=1 --<<Ref-No2>>
group by lphshopid, lphBillid, lphBillNo,lphbilldate, lpditemid,updatetime, lpdItemUnitPrice, lpdItemQuantity, 
	lphdepexrate,lphExchangerate            
            
union all            
            
--write off            
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whid, wh.whno,            
convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty, 'Write off' TYpe, -1 mode,             
updatetime, wdCostPrice,             
wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,        
'' CustomerNAme,0 SellingPrice,0 sellingperUnit,0 Margin,'' CustID             
from loswriteoffheader wh, loswriteoffdetail wd            
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and whtype<>'I'   --Ref-No1   
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,             
whDepExrate, whConExrate            
            
union all 

--In-House Cons  --Ref-No1            
select wh.whshopid, wd.wditemid, wh.whdate sdate, wh.whid, wh.whno,            
convert(numeric(18,3),sum(wd.wdWriteoffQty)) as writeoffqty, 'In-House Cons' TYpe, -1 mode,             
updatetime, wdCostPrice,             
wdCostPrice * whdepexrate depCostPrice, wdCostPrice * whConExrate ConCostPrice,        
'' CustomerNAme,0 SellingPrice,0 sellingperUnit,0 Margin,'' CustID             
from loswriteoffheader wh, loswriteoffdetail wd            
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0 and whtype='I' and whVerified=1 
group by wh.whshopid, wh.whDate, wh.whid, wh.whno, wd.wditemid,updatetime, wdCostPrice,             
whDepExrate, whConExrate            
            
union all             
            
--Deapatch            
select dd.dgdshopid, dd.dgditemid, dh.dghDate sdate, dh.dghid, dh.dghNo,            
convert(numeric(18,3),sum(dd.dgddespatchedgoodqty)) as despatchqty,             
'Despatch To Godown' TYpe, -1 mode,updatetime, dgdCostPrice,             
dgdCostPrice * dghdepexrate depCostPrice, dgdCostPrice * dghConExrate ConCostPrice,        
'' CustomerNAme,0 SellingPrice,0 sellingperUnit,0 MArgin,'' CustID             
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd             
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0             
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish             
group by dd.dgdshopid, dh.dghdate, dh.dghid, dh.dghNo,dd.dgditemid,updatetime,             
dgdCostPrice, dghdepexrate, dghconexrate            
            
union all            
            
--Transferout            
select todshopid, toditemid, tohDate sdate, tohid, tohno,            
convert(numeric(18,3),sum(todissuedgoodqty)) as ToutQty , 'Transfer Out' Type,             
-1 mode,updatetime, todCostPrice,             
todCostPrice * tohdepexrate depCostPrice, todCostPrice * tohConExrate ConCostPrice,        
'' CustomerNAme,0 SellingPrice,0 sellingperUnit,0 MArgin,'' CustID             
 from mestransferoutheader , mestransferoutdetail  where            
tohid=todid and Tohshopid=todshopid and tohcancelled=0            
and tohtransfinished = 1 -- for the concept of stock updation after transaction finish             
group by todshopid, tohdate, tohid, tohno, todItemid,updatetime, todCostPrice,             
tohdepexrate, tohConExrate            
            
union all            
            
--recovery minus            
select sr.srshopid, sr.sritemid, sr.srdate sdate, sr.srid,             
'Rec' + convert(varchar(50), sr.srid) srno,            
convert(numeric(18,3),sum(isnull(sr.srdedstock,0)))  as recAdd, 'Recovery Minus' type,             
1 Mode, updatetime, srCostPrice,             
srcostprice * srdepexrate depCostPrice, srcostprice * srconexrate ConCostPrice,        
'' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'' CustID from             
losstockrecovery sr group by  sr.srshopid, sr.srdate, sr.srid,  sr.sritemid,updatetime,             
srCostPrice, srdepexrate, srconexrate having sum(isnull(sr.srdedstock,0)) >0            
            
union all            
            
--stockverification minus            
select svdshopid, svdItemid, svhDate sdate, svhid, svhno,            
convert(numeric(18,3),sum(svdAvailStock-svdVerifiedStock)) as svMinusQty,             
'Verification Minus' type, -1 mode,updatetime, svdCostPrice,            
svdCostPrice * svhdepexrate depCostPrice, svdCostPrice * svhconexrate ConCostPrice,        
'' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'' CustID              
from  losstockverificationheader, losstockverificationdetail where            
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock            
and svhCancelled=0 group by  svdShopID, svhdate, svhid, svhno, svdItemid,updatetime,             
svdCostPrice, svhdepexrate , svhconexrate             
  union all            
            
--pos sales            
select poshShopID, posditemid, poshBilldate sdate, poshbillid, poshBillNo,            
convert(numeric(18,3),sum(isnull(posdquantity,0))) cashsales,             
'Cash Sales' as type, -1 mode,updatetime, posdCostPrice,             
posdCostPrice * poshdepexrate depCostPrice,             
posdCostPrice * poshExchangeRate ConCostPrice,        
poshCustomerName CustomerName,posdUnitPrice SellingPrice,  
--posdBlockPrice sellingperUnit,   'benzigar 16/09/2009 commented this and added the below  
posdUnitPrice/posdQuantity  sellingperUnit,      
case   posdUnitPrice when 0 then 0        
else         
((posdUnitPrice-(posdCostPrice * poshExchangeRate))/posdUnitPrice)*100  end Margin,'' CustID          
 from losposdetail,losposheader             
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0 group by            
poshshopid, poshbillid, poshBillNo, poshbilldate, poshbillid, poshBillNo,             
posditemid,updatetime, posdCostPrice, poshdepexrate, poshExchangeRate,poshCustomerName ,posdUnitPrice,posdBlockPrice,  
posdQuantity    -- benzigar 16/09/2009 added      
            
union all            
            
--credit invoice            
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceid, ihInvoiceNo,             
convert(numeric(18,3),sum(isnull(idquantity,0))) as creditsales, 'Credit Sales' Type,             
-1 mode,updatetime, idCostPrice, idCostPrice * ihdepexrate depCostPrice,             
idCostPrice * ihExchangeRate ConCostPrice,        
CustomerName,idUnitPrice SellingPrice,  
--idBlockPrice sellingperUnit, 'benzigar 16/09/2009 commented this and added the below  
idUnitPrice/idQuantity sellingperUnit,       
case idUnitPrice when 0 then 0        
else ((idUnitPrice-(idCostPrice * ihExchangeRate))/idUnitPrice)*100 end Margin,ihCustomerID CustID        
from losinvoicedetail,losinvoiceheader,aCustomerMaster            
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0            
and ihType ='I' and ihCustomerID=CustomerID group by ihshopid, ihinvoicedate, ihInvoiceid, ihInvoiceNo, iditemid,             
updatetime, idCostPrice, ihdepexrate, ihExchangeRate,CustomerName,idUnitPrice,idBlockPrice,ihCustomerID,  
idQuantity  -- benzigar 16/09/2009 added              
            
union all            
            
--exchange out            
select sehShopID, seditemid, sehExchangeDate sdate, sehexchangeid, sehexchangeno,             
convert(numeric(18,3),sum(isnull(sedquantity,0)))  as exchangedout ,             
'Exchange Out' Type, -1 mode,updatetime, sedCostPRice,            
sedCostPrice * sehdepexrate depCostPrice, sedCostPrice * sehExchangerate ConCostPrice,        
'' CustomerNAme,0 SellingPrice,0 sellingperUnit,0 Margin,'' CustID                
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID             
and sedShopID=sehShopid and sedBillorExchange='E' and SEHCANCELLED=0            
group by sehShopID, sehExchangeDate, sehexchangeid, sehexchangeno, seditemid,updatetime,             
sedCostPRice, sehdepexrate, sehExchangerate             
            
union all            
            
--special invoice return to shop            
select IhShopid, iditemid, ihInvoicedate sdate, ihInvoiceid, ihInvoiceNo,             
convert(numeric(18,3),-sum(isnull(reqqty,0)))   as SpecialReturn, 'Special Invoice Return' Type,             
1 mode,updatetime, idCostPrice,             
idCostPrice * ihdepexrate depCostPrice, idCostPrice * ihExchangerate ConCostPrice,        
'' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin, ihCustomerID CustID              
from losspecialinvoicedetail, losspecialinvoiceheader            
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1            
and ihproforma=0 and ihTransFinished = 1 group by ihshopid, ihinvoicedate, ihInvoiceid,             
ihInvoiceNo, iditemid, updatetime, idCostPrice, ihdepexrate, ihExchangerate,ihCustomerID            
 -- transfinished added as stock is updated only after confirming            
            
union all            
            
 --COMMENTED AS MODIFICATIONS ON SERVICE IS GOING ON. TO BE REMOVED ONCE IT IS COMPLETED            
  select serinvhShopid, repinvdpartsid, serinvhdate , serinvhid , serinvNo ,             
  convert(numeric(18,3) , sum(repinvdqty)) , 'Parts Replaced' type,            
  -1 as mode, serinvhupdatetime, repinvdcostprice,             
repinvdCostPrice * seinvhdepexrate depCostPrice, repinvdCostPrice * serinvhcmpexrate ConCostPrice,        
'' CustomerName,0 SellingPrice,0 sellingperUnit,0 Margin,'' CustID            
  from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid              
  and serinvhshopid = repinvdshopid AND serinvhcancelled=0             
  group by serinvhShopid,  serinvhdate , serinvhid , serinvNo ,  repinvdpartsid,             
 serinvhupdatetime, repinvdcostprice, seinvhdepexrate, serinvhcmpexrate            
            
  union all            
             
--Re-Exporting            
select rehShopID, reditemid, rehExportDate sdate, rehExportID, rehExportNo,             
convert(numeric(18,3),sum(isnull(redquantity,0)))  as creditsales, 'Re-Export' Type,             
-1 mode, rehUpdatetime, redCostPrice,             
redCostPrice * rehdepexrate depCostPrice, redCostPrice * rehExchangerate ConCostPrice,        
'' CustomerNAme,0 SellingPrice,0 sellingperUnit,0 Margin,'' CustID           
from losexportdetail, losexportheader            
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0            
and rehType='I' group by rehShopID, rehExportDate, rehExportID, rehExportNo, redItemID,             
rehUpdatetime, redCostPrice, rehdepexrate, rehExchangerate            
            
union all          
          
-----Hire Purchase Invoice          
select hpqhShopid,hpqdItemId,hpqhQuotationDate sDate,hpqhQuotationID,hpqhQuotationNo,1 as Qty, 'Hire Purchase' Type,          
-1 mode,hpqhUpdatetime,hpqdCostPrice,hpqdCostPrice*1 depCostPrice,hpqdCostPrice*1 ComCostPrice,        
CustomerName CustomerName,hpqdSellingPrice SellingPrice,hpqdSellingPrice sellingperUnit,((hpqdSellingPrice-hpqdCostPrice)/hpqdSellingPrice)*100 Margin,hpqhCustomerID CustID           
from loshpInvoiceDetail,losHpInvoiceHeader,acustomerMAster where hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and          
hpqhCancel=0 and hpqhType='I' and CustomerID=hpqhCustomerID group by hpqhShopid,hpqhQuotationDate,hpqhQuotationID,hpqhQuotationNo,hpqdItemId,          
hpqhUpdatetime,hpqdCostPrice,CustomerName,hpqdSellingPrice,hpqdSellingPrice,hpqhCustomerID)          
          
 shopbin            
group by shopid, itemid, sdate , Transno, TransID , Transqty, Type, mode,updatetime, Costprice,depcostprice,concostprice,CustomerNAme,SellingPrice,Margin,CustID,sellingperUnit           
             
        
      

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_030
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

GO

/****** Object:  View [dbo].[vwSupplierLedger]    Script Date: 03/27/2012 14:32:57 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSupplierLedger]'))
DROP VIEW [dbo].[vwSupplierLedger]
GO


/****** Object:  View [dbo].[vwSupplierLedger]    Script Date: 03/27/2012 14:32:57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

      
-- Modified on  :  25/11/2003                          
-- Modified by  :  Kishore                          
-- Comments  :  Added multivendor option. (25/08/2003)                          
--                      :  Added the credit amount change (28/02/2003)                          
--                      :  Removed the reducing discount from bill amount                          
--                         from HQ Bills (13/06/2003)                                
--                      :  Taken bill amount now as bill amount + lc amount                           
--                         Added query to take LC payment (05/09/2003)                          
--                      :  Added the IsNull b4 taking pbhLcAmount (17/09/2003)                          
--                      :  Replaced the pddAmount with pddCustomerAmount in lc payment (19/09/2003)                          
--                      :  on re-export given invoice type only ...(10/10/2003)                          
--                      :  Added Paid Amount column (25/11/2003)                          
--   : adjustment entry added                          
--Verified by       : Hariharan                           
--Verified Date      : 04/05/2004 (verified From Client DB)                          
-------------------------------------------------------------------------------------                      
                    
-- Modified on  :  21/06/2008                         
-- Modified by  :  Shinu                    
-- Purpose :  Added Purchase Returns Also                      
                    
--------------------------------------------------------------------------------                        
-- Modified on  :  06/07/2010                         
-- Modified by  :  Regin                  
-- Purpose      :                    
-- Since discount is already considered in lphbillamount,                   
-- it should not be deducted by lphdiscount once again.                  
-- Reference    : RefNo-1                  
--------------------------------------------------------------------------------                
--Altered by Sreejith G A              
--Altered on 20100827              
--Added the condition  'and b.lphConfirmed=1' to this view to populate only confirmed Local Purchase Bills              
--------------------------------------------------------------------------------            
--RefNo:01            
--Modified By : VinothMurugan V.            
--Date    : 14/10/2010            
--Purpose   : Adding Interdivisional Bills and adding confirm bit            
--------------------------------------------------------------------------------    
----Modified By : jyothish   
 --RefNo:02         
--Date    : 01/12/2011            
--Purpose   : correted HQ purchase bills  total amount      
--------------------------------------------------------------------------------      
--Reference No	:	RefNo:3 
--Modified By	:	MANUNADH.U
--Modified On	:	26/03/2012
--Purpose		:	Add the condition to filter local purchase bill with lphConfirmed=1
--------------------------------------------------------------------------------
CREATE view [dbo].[vwSupplierLedger] AS                          
                
-- account bills                                    
select b.CompanyId, b.DepartmentId , b.VendorId, b.billdate tDate,isnull(max(vw.refno),'') as SecRef,                            
	b.billsno tNo, isnull(b.Referenceno,'') Cr, 'A Bill' as Type, b.Remarks,sum(bd.amount) as BillAmt, 0.0 as PmtAmt,                           
	dateadd(dd, b.dueperiod,b.billdate) DueDate, datediff(dd,b.billdate,getdate()) Age,b.UpdateTime,                          
	max(vw.setdate) SetDate,convert(numeric(18,2), sum(bd.amount) * b.ExchangeRate) cBillAmt,0.0 cPmtAmt,FinancialId,
	convert(numeric(18,2), sum(bd.amount) * b.DepExRate) dBillAmt,0.0 dPmtAmt, CreditorAccId, b.ExchangeRates, 
	Sum(vw.PaidAmount) PaidAmount                          
from aVendorMaster v, billsdebitdetails bd, bills b                           
	left outer join vwbillsettlementno vw on b.CompanyId = vw.CompanyId and b.billsid = vw.billid                           
where v.VendorId = b.VendorId and b.CompanyId = bd.CompanyId and b.billsid = bd.billsid and b.cancelled =0 and                     
	b.CashPurchase =0                           
group by b.CompanyId, b.BillsID, b.DepartmentId, b.VendorId, creditoraccid, b.billsno, b.remarks,b.referenceno, 
	b.billdate, b.updatetime, b.dueperiod, b.ExchangeRate, b.DepExRate,  financialid,b.exchangerates                          
                          
union all                           
                          
--HQ purchase bills   RefNo:02                 
select b.pbhCompanyId, b.pbhDepartmentId, b.pbhVendorId, b.pbhbilldate tdate,isnull(vw.refno,'') as secref,                    
	b.pbhbillno tno, isnull(b.pbhvendorRefNo,'') cr, 'P Bill' as type,b.pbhremarks, (pbhbillamount ) as billamt, 
	0.0 as pmtamt,pbhDueDateforPayment duedate, datediff(dd,b.pbhbilldate,getdate()) age,b.updatetime, vw.setdate,                  
	convert(numeric(18,2),((b.pbhbillamount ) * b.pbhExchangeRate)) cbillamt,0.0 cpmtamt, pbhFinancialID,                  
	convert(numeric(18,2),((b.pbhbillamount ) * b.pbhDepExRate)) dbillamt, 0.0 dpmtamt,creditoraccid, 
	b.pbhexchangerates, PaidAmount                  
from aVendorMaster v, losppurchasebillheader b                   
	left outer join vwPurchasebillsettlementno vw on b.pbhCompanyId = vw.CompanyId and b.pbhbillid = vw.billid                   
where v.VendorId = b.pbhVendorId and b.pbhcancelled =0 and b.pbhcashpurchase=0                  
                  
union all                          
-- Since discount is already considered in lphbillamount,                   
-- it should not be deducted by lphdiscount once again. (RefNo-1)                  
select b.lphCompanyId, b.lphDepartmentId, b.lphVendorId, b.lphbilldate tdate,isnull(vw.refno,'') as secref,                            
	b.lphbillno tno, isnull(b.lphvendorbillNo,'') cr, 'LP Bill' as type, b.lphremarks,                           
	-- (lphbillamount- isnull(lphdiscount,0)) as billamt                  
	lphbillamount as billamt,0.0 as pmtamt,lphDueDateforPayment duedate, datediff(dd,b.lphbilldate,getdate()) age,
	b.updatetime, vw.setdate,-- convert(numeric(18,2), ((lphbillamount- isnull(lphdiscount,0)) * lphExchangeRate)) cBillAmt                           
	convert(numeric(18,2), (lphbillamount * lphExchangeRate)) cBillAmt, 0.0 cpmtamt, lphFinancialID,                          
	-- convert(numeric(18,2), ((lphbillamount- isnull(lphdiscount,0)) * lphDepExRate)) dBillAmt,                           
	convert(numeric(18,2), (lphbillamount * lphDepExRate)) dBillAmt,0.0 dpmtamt, v.creditoraccid, b.lphexchangerates, 
	PaidAmount                          
from aVendorMaster v, loslocalpurchaseheader b 
	left outer join vwlocalPurchasebillsettlementno vw on b.lphCompanyId = vw.CompanyId and b.lphshopid = vw.shopid 
		and b.lphbillid = vw.billid   
where v.VendorId = b.lphVendorId and b.lphcancelled =0  and lphcashpurchase=0 AND B.lphConfirmed=1 --<<RefNo:3>>  --Local purchase bills                   
--                          
union all                          
--                          
select ph.phCompanyId, ph.phDepartmentId, ph.phVendorId, ph.phpaymentdate tdate,'' as secref,ph.phpaymentno tno,'' cr,
	'Payment' type, ph.phremarks, 0.0  billamt,ph.phcustomeramount pmtamt, null duedate, 0 age, ph.updatetime, null, 
	0.0 cbillamt,isnull(convert(numeric(18,2), (ph.phamount -(isnull(ph.phdebitamount,0)*                           
	isnull(ph.vencusaccexrate,0))) * phExchangeRate),0) cpmtamt,phfinancialid,  0.0 dbillamt, 
	isnull(convert(numeric(18,2), (ph.phamount - (isnull(ph.phdebitamount,0)* isnull(ph.vencusaccexrate,0))) * 
	phDepExRate),0) dpmtamt,creditoraccid, ph.phexchangerates, 0 PaidAmount                          
from aVendorMaster v, ahqpaymentvoucherheader ph                           
where v.VendorId = ph.phVendorId and ph.phcancelled = 0 and phVendorId is not null and phlcpayment='OP'  --RefNo:01                        
--                          
union all                          
--                          
select rh.CompanyId, rh.DepartmentId, rh.VendorId, rh.receiptdate tdate, '' as secref, rh.receiptno tno, '' cr,                           
	'Refund' type, rh.remarks, rh.customeramount billamt, 0.0 pmtamt , null duedate, 0 age, rh.updatetime, null,                           
	isnull(convert(numeric(18,2),(rh.amount -(isnull(rh.creditamount,0)* isnull(rh.cusvenaccexrate,0))) *                           
	rh.ExchangeRate),0) cbillamt, 0.0 cpmtamt, financialid ,                          
	isnull(convert(numeric(18,2),(rh.amount -(isnull(rh.creditamount,0)* isnull(rh.cusvenaccexrate,0))) *                           
	rh.DepExRate),0) dbillamt, 0.0 dpmtamt, v.creditoraccid, rh.exchangerates, PaidAmount                          
from aVendorMaster v, receiptvoucherheader rh  
	Left Outer Join vwReceiptSettlementNo vw on rh.companyid = vw.companyid and rh.ReceiptId = vw.ReceiptId                           
		and rh.VendorId = vw.VendorId                          
where v.VendorId = rh.VendorId and rh.cancelled = 0 and rh.VendorId is not null                          
--                          
union all                          
--                          
select dcn.dcnCompanyId, dcn.dcnDepartmentId, dcn.dcnVendorId, dcn.dcndate tdate, isnull(vw.refno,'') as secref,                           
 dcn.dcnno tno,'' cr, 'Credit Note' type, dcn.dcndetails remarks, dcn.dcnamount billamt, 0.0 pmtamt, null duedate,                           
 datediff(dd,dcn.dcndate,getdate()) age, dcn.updatetime, vw.setdate,                          
 convert(numeric(18,2),dcn.dcnamount * dcn.dcnExchangeRate) cbillamt, 0.0 cpmtamt, dcnfinancialid,                           
 convert(numeric(18,2),dcn.dcnamount * dcn.dcnDepExRate) dbillamt, 0.0 dpmtamt,                           
 v.creditoraccid, dcn.dcnexchangerates, PaidAmount                          
from aVendorMaster v, debitcreditnote dcn 
	left outer join vwcreditnotesettlementno vw on dcn.dcnCompanyId = vw.CompanyId and dcn.dcnid = vw.dcnid                           
where v.VendorId = dcn.dcnVendorId and dcn.dcncancelled =0 and dcn.dcnVendorId is not null and dcn.dcndebit =0  --RefNo:01                        
--                          
union all                          
--                          
select dcn.dcnCompanyId, dcn.dcnDepartmentId,  dcn.dcnVendorId, dcn.dcndate tdate, '' as secref, dcn.dcnno tno,                           
	'' cr, 'Debit Note' type, dcn.dcndetails remarks, 0.0 billamt, dcn.dcnamount pmtamt, null duedate, 0 age,   
	dcn.updatetime, null, 0.0 cbillamt, convert(numeric(18,2),dcn.dcnamount * dcnExchangeRate) cpmtamt, dcnfinancialid                          
	, 0.0 dbillamt, convert(numeric(18,2),dcn.dcnamount * dcnDepExRate) cpmtamt,creditoraccid, dcn.dcnexchangerates, 
	0 PaidAmount                          
from aVendorMaster v, debitcreditnote dcn                           
where dcn.dcncancelled =0 and dcn.dcnVendorId is not null and dcn.dcndebit =1 and v.VendorId = dcn.dcnVendorId   --RefNo:01                       
--                          
union all                          
--                          
select dcn.losdcnCompanyId, dcn.losdcnDepartmentId, dcn.losdcnVendorId, dcn.losdcndate tdate, '' as secref,                           
	dcn.losdcnno tno,'' cr, 'Shop Credit Note' type, dcn.losdcnremarks remarks, dcn.losdcnamount billamt,                           
	0.0 pmtamt, null duedate, datediff(dd,dcn.losdcndate,getdate()) age, dcn.updatetime, null,                      
	convert(numeric(18,2),dcn.losdcnamount * dcn.losExchangeRate) cbillamt, 0.0 cpmtamt, losfinancialid,                          
	convert(numeric(18,2),dcn.losdcnamount * dcn.losDepExRate) dbillamt, 0.0 dpmtamt,                           
	creditoraccid, dcn.losdexchangerates, 0 PaidAmount                          
from aVendorMaster v, losdebitcreditnote dcn                           
where v.VendorId = dcn.losdcnVendorId and                           
	dcn.losdcncancelled =0 and dcn.losdcnVendorId is not null and dcn.losdcndebit =0                          
--                          
union all                          
--                          
select dcn.losdcnCompanyId, dcn.losdcnDepartmentId,  dcn.losdcnVendorId, dcn.losdcndate tdate, '' as secref,                           
	dcn.losdcnno tno, '' cr, 'Shop Debit Note' type, dcn.losdcnremarks remarks, 0.0 billamt, dcn.losdcnamount pmtamt,                           
	null duedate, 0 age, dcn.updatetime, null, 0.0 cbillamt, convert(numeric(18,2),dcn.losdcnamount * losExchangeRate) cpmtamt,                           
	losfinancialid, 0.0 dbillamt, convert(numeric(18,2),dcn.losdcnamount * losDepExRate) dpmtamt,                           
	creditoraccid, dcn.losdexchangerates, 0 PaidAmount                          
from aVendorMaster v, losdebitcreditnote dcn                           
where v.VendorId = dcn.losdcnVendorId and                           
	dcn.losdcncancelled =0 and dcn.losdcnVendorId is not null and dcn.losdcndebit =1                           
--                          
union all                          
--                          
-- RE EXPORT DONE FOR VENDOR TO CONSIDER AS ADVANCE - HARI 021225                          
                          
select rehCompanyId, rehDepartmentId,  rehVendorId, rehExportDate tdate, '' as secref,rehExportNo tno, '' cr, 
	'Re-Export' type, rehRemarks remarks, 0.0 billamt,rehExportAmount pmtamt, null duedate, 0 age, rehUpdatetime, 
	null, 0.0 cbillamt,convert(numeric(18,2),rehexportamount* rehExchangeRate) cpmtamt,rehfinancialid, 0.0 dbillamt, 
	convert(numeric(18,2),dcn.rehExportamount * rehDepExRate) dpmtamt,creditoraccid, dcn.rehexchangerates,0 PaidAmount                          
from aVendorMaster v, losexportheader dcn                           
where v.VendorId = rehVendorId and rehCancelled =0 and rehVendorId is not null and rehtype like '%i%'                          
--                          
union all                          
--                           
-- HQ Payment (Multiple Vendor)                
select ph.phCompanyId, ph.phDepartmentId, pd.pvdVendorId, ph.phpaymentdate tdate,'' as secref, ph.phpaymentno tno, 
	'' cr,'Payment' type, ph.phremarks, 0.0  billamt, pd.pvdVendorAmount pmtamt,null duedate, 0 age, ph.updatetime, 
	null, 0.0 cbillamt,isnull(convert(numeric(18,2), pd.pvdAmount * phExchangeRate),0) cpmtamt,phfinancialid,                           
	0.0 dbillamt, isnull(convert(numeric(18,2),pd.pvdAmount * phDepExRate),0) dpmtamt,                           
	CreditorAccId, ph.phexchangerates, 0 PaidAmount                          
from ahqpaymentvoucherheader ph, aHQPaymentVoucherVendorDetails pd, aVendorMaster v                          
where ph.phCompanyId = pd.pvdCompanyId and ph.phPaymentID = pd.pvdPaymentid and ph.phVendorId = v.VendorId  and 
	ph.phcancelled = 0 and ph.phpaidbyVendorId is not null and phlcpayment = 'OP'    --RefNo:01                           
                          
Union All                          
                          
-- take LC (HARI modified removing ahqpaymentvoucherdebitdetails and losppurchase billheader                          
select ph.phCompanyId, ph.phDepartmentId, ph.phVendorId, ph.phpaymentdate tdate,'' as secref,ph.phpaymentno tno,'' cr, 
	'Payment' type, ph.phremarks, 0.0  billamt,ph.phcustomeramount pmtamt, null duedate, 0 age, ph.updatetime, null, 
	0.0 cbillamt,isnull(convert(numeric(18,2), (ph.phamount -(isnull(ph.phdebitamount,0)*                           
	isnull(ph.vencusaccexrate,0))) * phExchangeRate),0) cpmtamt,phfinancialid,  0.0 dbillamt, 
	isnull(convert(numeric(18,2),(ph.phamount - (isnull(ph.phdebitamount,0)* isnull(ph.vencusaccexrate,0))) * 
	phDepExRate),0) dpmtamt,creditoraccid, ph.phexchangerates, 0 PaidAmount                          
from aVendorMaster v, ahqpaymentvoucherheader ph , MiscSettings s                          
where v.VendorId = ph.phVendorId and ph.phcancelled = 0 and phVendorId is not null and ph.phLcPayment in ('LCM', 'LCO')                          
	and s.LcToAccount = 0   and ph.phConfirmed = 1 --RefNo:01                           

union all                          
-- FOR TAKING THE ADJUSTMENT ENTRIES IN CUSTOMER BALANCE TO REMOVE THE DIFFERENCES                          
select ah.CompanyId, ah.DepartmentId , ad.vendorid, ah.adjustmentdate tDate,'' as SecRef,ah.adjustmentno tNo, '' Cr, 
	'Adj' as Type, ah.Remarks,0 as BillAmt, 0.0 as PmtAmt,null DueDate, 0 Age, ah.adjustmentdate UpdateTime, 
	null SetDate,case JournalCredit when 1 then ConsAmount else 0.00 end cBillAmt,
	case JournalCredit when 0 then ConsAmount else 0.00 end  cPmtAmt, FinancialId,                             
	case JournalCredit when 1 then ad.Amount else 0.00 end dBillAmt,                           
	case JournalCredit when 0 then ad.Amount else 0.00 end dPmtAmt,creditorAccId, ah.ExchangeRates, 0 PaidAmount                          
from adjustmentheader ah, adjustmentdetails ad, aVendorMaster v                        
where ah.AdjustmentID = ad.AdjustmentID and ah.companyid = ad.companyid                           
	and ah.Cancelled = 0 and  ad.Vendorid is not null and ad.vendorid = v.vendorid                        
                    
union all                       
                       
--Purchase Return                          
select prhCompanyId, PrhDepartmentId,  PrhVendorId, PrhReturndate tdate, '' as secref, PrhReturnNo tno,                           
	'' cr, 'Purchase Return' type, prhRemarks remarks, 0.0 billamt, sum(prdSuppamount) pmtamt, null duedate, 0 age,                           
	prhReturnupdatetime, null, 0.0 cbillamt, convert(numeric(18,2),sum(prdSuppamount) * prhExRate) cpmtamt, \
	Prhfinancialid,0.0 dbillamt, convert(numeric(18,2),sum(prdSuppamount) * prhDepExRate) cpmtamt,                           
	creditoraccid, prhexchangerates, 0 PaidAmount                          
from aVendorMaster v, lopurchaseReturnheader,loPurchaseReturnDetail                            
where prhCompanyId=prhCompanyId And PrhReturnID=PrdReturnID And Prhcancelled =0 and PrhVendorId is not null                          
	and v.VendorId = PrhVendorId                     
Group By   prhCompanyId, PrhDepartmentId,  PrhVendorId, PrhReturndate, PrhReturnNo, prhReturnupdatetime,                          
	prhExRate,Prhfinancialid, creditoraccid, prhexchangerates,prhremarks,prhdepexrate       
            
union all            
----------------------------------------------------------------------------------------------RefNo:01            
select b.CompanyId, b.DepartmentId , b.VendorId, b.billdate tDate,isnull(max(vw.refno),'') as SecRef,                            
	b.billsno tNo, isnull(b.Referenceno,'') Cr, 'Indiv Bill' as Type, b.Remarks,sum(bd.amount) as BillAmt, 
	0.0 as PmtAmt,dateadd(dd, b.dueperiod,b.billdate) DueDate, datediff(dd,b.billdate,getdate()) Age,                          
	b.UpdateTime,max(vw.setdate) SetDate,convert(numeric(18,2), sum(bd.amount) * b.ExchangeRate) cBillAmt,                           
	0.0 cPmtAmt, FinancialId,convert(numeric(18,2), sum(bd.amount) * b.DepExRate) dBillAmt,                           
	0.0 dPmtAmt, CreditorAccId, b.ExchangeRates, Sum(vw.PaidAmount) PaidAmount                          
from aVendorMaster v, interdivisionbillsdetails bd, interdivisionbillsheader b                           
	left outer join vwInterdivBillSettlementNo vw on b.CompanyId = vw.CompanyId and b.billsid = vw.InterdivBillID                           
where v.VendorId = b.VendorId and b.CompanyId = bd.CompanyId and b.billsid = bd.billsid and b.cancelled =0 and                          
	b.CashPurchase =0                           
group by b.CompanyId, b.BillsID, b.DepartmentId, b.VendorId, creditoraccid, b.billsno, b.remarks,                           
 b.referenceno, b.billdate, b.updatetime, b.dueperiod, b.ExchangeRate, b.DepExRate,  financialid,b.exchangerates                          
-------------------------------------------------------------------------------------------- 

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_030
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

/****** Object:  View [dbo].[vwUnConfirmedTransactions]    Script Date: 03/24/2012 17:23:17 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwUnConfirmedTransactions]'))
DROP VIEW [dbo].vwUnConfirmedTransactions
GO


-- Created by : Hariharan     
-- Created on : 19/01/2004 (at Male' From V2)    
-- Comments   : For alert display of unconfirmed transactions    
-- =================================================================       
-- Ref.No:1
-- Upgraded By : AADYAKUMAR D V      
-- Upgraded On : 13-03-2012        
-- Upgrade     : Added more transactions     
-- ==================================================================       
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
    
Create VIEW dbo.vwUnConfirmedTransactions AS    
    
SELECT 'Despatch Note Generation' TransactionType, dnmDespatchNoteId TransactionId,    
dnmDespatchNoteNo TransactionNo, dnmDespatchNoteDate TransactionDate,     
0 LocationId, 'HQ' LocationName, Departmentid, 'H' LocType    
FROM aHqDespatchNoteMain Main LEFT OUTER JOIN aHqDespatchNoteHeader Header    
ON Main.dnmDespatchNoteId = Header.dhDespatchNoteMainID    
WHERE dnmCancelled = 0 AND dhTransFinished = 0 group by     
dnmDespatchNoteId, dnmDespatchNoteNo, dnmDespatchNoteDate, Departmentid    
    
    
UNION ALL    
    
SELECT 'Issue Note Generation' TransactionType, inmIssueNoteId TransactionId,    
inmIssueNoteNo TransactionNo, inmIssueDate TransactionDate,     
0 LocationId, 'HQ' LocationName, Departmentid, 'H' LocType    
FROM aHqIssueNoteMain Main LEFT OUTER JOIN aHqIssueNoteHeader Header    
ON Main.inmIssueNoteId = Header.inhIssueNoteMainId    
    
WHERE inmCancel = 0    
AND inhTransFinished = 0 group by inmIssueNoteId ,    
inmIssueNoteNo, inmIssueDate, Departmentid    
    
UNION ALL    
    
    
SELECT 'Costing', chCostingId, chCostingNo, chCostingDate, 0, 'HQ', chDepartmentId, 'H' LocType    
FROM loaCostingHeader WHERE chCancelled = 0 AND chCostingDone = 0    
and chCostingId >0    
    
UNION ALL    
    
SELECT 'Local Purchase Costing', lpchCostingId, lpchCostingNo, lpchDate, 0, 'HQ',     
lpchDepartmentid, 'H' LocType FROM loaLocalPurchaseCostingHeader    
WHERE lpchCancelled = 0    
AND lpchCostingDone = 0    
    
UNION ALL    
    
SELECT 'Item Split Costing', scfhId, scfhNo, scfhDate, 0, 'HQ', scfhdepartmentid, 'H' LocType    
FROM loaItemSplitCostingHeader    
WHERE scfhCancelled = 0    
AND scfhCostFixed = 0    
    
UNION ALL    
    
SELECT 'Goods Arrival To Godown', ahArrivalId, ahArrivalNo, ahArrivalDate,     
ahLocalGodownId, aGodown.GodownName, ahDepartmentid, 'G' LocType    
FROM loiArrivalHeader LEFT OUTER JOIN aGodown    
ON ahLocalGodownId = GodownId    
WHERE ahCancelled = 0    
AND ahTransFinished = 0    
    
UNION ALL    
    
    
SELECT 'Despatch To Shop', dhDespatchId, dhDespatchNo, dhDespatchDate,     
dhGodownId, GodownName, dhDepartmentId, 'g' LocType    
FROM meiDespatchToShopHeader LEFT OUTER JOIN aGodown    
ON dhGodownId = GodownId    
WHERE dhCancelled = 0    
AND dhTransFinished = 0    
    
UNION ALL    
    
SELECT 'Godown To Godown Transfer', gthDespatchId, gthDespatchNo, gthDespatchDate,     
gthFromGodownId, GodownName, gthDepartmentId, 'H' LocType    
FROM meiGOdownTransferHeader LEFT OUTER JOIN aGodown    
ON gthFromGodownId = GodownId    
WHERE gthCancelled = 0 AND gthTransFinished = 0    
    
UNION ALL    
    
SELECT 'Goods Arrival To Shop', gahArrivalId, gahArrivalNo, gahArrivalDate,     
gahShopId, ShopName, gahDepartmentId, 'S' LocType    
FROM LOsGoodsArrivaltoShopHeader LEFT OUTER JOIN aShops    
ON gahShopId = ShopId    
WHERE gahCancelled = 0    
AND gahTransFinished = 0    
    
UNION ALL    
    
--SELECT 'Request To Shop', srhRequestId, srhRequestNo, srhRequestDate,     
--srhShopId, ShopName, Departmentid , 'S' LocType    
--FROM mesRequestToShopHeader LEFT OUTER JOIN aShops    
--ON srhShopId = aShops.ShopId    
--WHERE srhCancelled = 0    
--AND srhTransFinished = 0    
    
--UNION ALL    
    
SELECT 'Request To HQ', grhRequestId, grhRequestNo, grhRequestDate,     
grhShopId, ShopName, departmentid, 'S' LocType    
FROM mosGoodsRequestHeader LEFT OUTER JOIN aShops    
ON grhShopId = aShops.ShopId    
WHERE grhCancel = 0    
AND grhTransFinished = 0    
    
--UNION ALL    
    
--SELECT 'Transfer Out', tohId, tohNo, tohDate, tohShopId,    
--ShopName, tohDepartmentid, 'S' LocType    
--FROM mesTransferOutHeader LEFT OUTER JOIN aShops    
--ON tohShopId = aShops.ShopId    
--WHERE tohCancelled = 0    
--AND tohTransFinished = 0    
    
UNION ALL    
    
SELECT 'Transfer In', tihId, tihNo, tihDate, tihShopId,    
ShopName, tihDepartmentid, 'S' LocType    
FROM losTransferInHeader LEFT OUTER JOIN aShops    
ON tihShopId = aShops.ShopId    
WHERE tihCancel = 0    
AND tihTransFinished = 0    
    
UNION ALL    
    
SELECT 'Shop To Godown Transfer', dghID, dghNo, dghDate, dghShopId,    
ShopName, dghDepartmentid, 'S' LocType    
FROM mesDespatchtoGodownHeader LEFT OUTER JOIN aShops    
ON dghShopid = aShops.ShopId    
WHERE dghCancelled = 0 AND dghTransFinished = 0    
    
UNION ALL    
    
SELECT 'Special Invoice', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopId,    
ShopName, ihDepartmentid, 'S' LocType FROM losSpecialInvoiceHeader LEFT OUTER JOIN aShops    
ON ihShopId = aShops.ShopId WHERE ihCancelled = 0 AND ihTransFinished = 0 

--Ref.No:1------------------------------START----------------------------------------------------   
    
UNION ALL    

SELECT 'Local Purchase', lphBillID, lphBillNo, lphBillDate, lphShopID,  
ShopName, lphDepartmentID, 'S' LocType FROM loslocalpurchaseheader LEFT OUTER JOIN aShops  
ON lphShopID = aShops.ShopId WHERE lphCancelled = 0 AND lphConfirmed = 0 

UNION ALL    

SELECT 'Warrenty Claim', wchID, wchNo, wchDate, wchShopID,  
ShopName, DepartmentID, 'S' LocType FROM losWarrentyClaimHeader LEFT OUTER JOIN aShops  
ON wchShopID = aShops.ShopId WHERE wchCancelled = 0 AND wchConfirmed = 0 and wchType='WC'

UNION ALL    

SELECT 'Business Promotion', wchID, wchNo, wchDate, wchShopID,  
ShopName, DepartmentID, 'S' LocType FROM losWarrentyClaimHeader LEFT OUTER JOIN aShops  
ON wchShopID = aShops.ShopId WHERE wchCancelled = 0 AND wchConfirmed = 0 and wchType='BP'

UNION ALL    

SELECT 'Hire Purchase Invoice', hpqhQuotationID, hpqhQuotationNo, hpqhQuotationDate, hpqhShopID,  
ShopName, DepartmentID, 'S' LocType FROM losHpInvoiceHeader LEFT OUTER JOIN aShops  
ON hpqhShopID = aShops.ShopId WHERE hpqhCancel = 0 AND hpqhConfirmed = 0  

UNION ALL    
 
SELECT 'InHouse Return/Exchanged', IHRHID, IHRHNo, IHRHDate, IHRHShopID,  
ShopName, DepartmentID, 'S' LocType FROM LOs_InHouseCons_ReturnHeader LEFT OUTER JOIN aShops  
ON IHRHShopID = aShops.ShopId WHERE IHRHCancelled = 0 AND IHRHConfirmed = 0 

UNION ALL    

SELECT 'MerGing', lshID, lshNo, lshDate, lshShopID,  
ShopName, DepartmentID, 'S' LocType FROM losMergeHeader LEFT OUTER JOIN aShops  
ON lshShopID = aShops.ShopId WHERE lshCancelled = 0 AND lshTransFinished = 0  

UNION ALL    

SELECT 'Purchase Return', WhID, WhNo, WhDate, whShopID,  
ShopName, DepartmentID, 'S' LocType FROM losPurchaseReturnheader LEFT OUTER JOIN aShops  
ON whShopID = aShops.ShopId WHERE WhCancelled = 0 AND whtransfinished = 0  

UNION ALL    

--Invoice confirmation is not using in program 
--SELECT 'Credit Invoice', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopID,  
--ShopName, DepartmentID, 'S' LocType FROM losinvoiceheader LEFT OUTER JOIN aShops  
--ON ihShopID = aShops.ShopId WHERE ihCancelled = 0 AND ihtransfinished = 0 and ihType='I' 

--UNION ALL

SELECT 'Purchase Quotation', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopID,  
ShopName, DepartmentID, 'S' LocType FROM losinvoiceheader LEFT OUTER JOIN aShops  
ON ihShopID = aShops.ShopId WHERE ihCancelled = 0 AND ihtransfinished = 0 and ihType='Q' 

UNION ALL

SELECT 'Purchase Order', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopID,  
ShopName, DepartmentID, 'S' LocType FROM losinvoiceheader LEFT OUTER JOIN aShops  
ON ihShopID = aShops.ShopId WHERE ihCancelled = 0 AND ihtransfinished = 0 and ihType='P' 

UNION ALL

SELECT 'Purchase Request', ihInvoiceID, ihInvoiceNo, ihInvoiceDate, ihShopID,  
ShopName, DepartmentID, 'S' LocType FROM losinvoiceheader LEFT OUTER JOIN aShops  
ON ihShopID = aShops.ShopId WHERE ihCancelled = 0 AND ihtransfinished = 0 and ihType='R'    

UNION ALL

SELECT 'Shop Consumption', WhID, WhNo, WhDate, whShopID,  
ShopName, DepartmentID, 'S' LocType FROM LOsWriteOffHeader LEFT OUTER JOIN aShops  
ON whShopID = aShops.ShopId WHERE WhCancelled = 0 AND whverified = 0 and whtype='I'

UNION ALL

SELECT 'Dummy POS', poshBillID, poshBillNo, poshBillDate, poshShopID,  
ShopName, DepartmentID, 'S' LocType FROM LOsPosdummyHeader LEFT OUTER JOIN aShops  
ON poshShopID = aShops.ShopId WHERE poshCancelled = 0 AND poshconfirmed = 0  

UNION ALL

SELECT 'SerialNo Verification', svhID, svhNo, svhDate, svhShopID,  
ShopName, DepartmentID, 'S' LocType FROM losSerialNoVerificationHeader LEFT OUTER JOIN aShops  
ON svhShopID = aShops.ShopId WHERE svhCancel = 0 AND cofirmed = 0 

UNION ALL

SELECT 'Stand By Issue', ishIssueID, ishIssueNo, ishDate, ishShopID,  
ShopName, DepartmentID, 'S' LocType FROM losSerStandByIssueHeader LEFT OUTER JOIN aShops  
ON ishShopID = aShops.ShopId WHERE ishCancelled = 0 AND ishConfirmed = 0  

UNION ALL

SELECT 'Special Invoice Quotation', IhInvoiceID, IhInvoiceNo, IhInvoiceDate, IhShopID,  
ShopName, DepartmentID, 'S' LocType FROM losSIQuotationHeader LEFT OUTER JOIN aShops  
ON IhShopID = aShops.ShopId WHERE IhCancelled = 0 AND ihTransFinished = 0  

UNION ALL

SELECT 'Request To Shop', srhRequestId, srhRequestNo, srhRequestDate,     
srhShopId, ShopName, Departmentid , 'S' LocType    
FROM mesRequestToShopHeader LEFT OUTER JOIN aShops    
ON srhShopId = aShops.ShopId    
WHERE srhCancelled = 0    
AND srhTransFinished = 0 and srhType='r'

UNION ALL

SELECT 'Inter Division Sales Request', srhRequestId, srhRequestNo, srhRequestDate,     
srhShopId, ShopName, Departmentid , 'S' LocType    
FROM mesRequestToShopHeader LEFT OUTER JOIN aShops    
ON srhShopId = aShops.ShopId    
WHERE srhCancelled = 0    
AND srhTransFinished = 0 and srhType='s'

UNION ALL

SELECT 'Transfer Out', tohId, tohNo, tohDate, tohShopId,    
ShopName, tohDepartmentid, 'S' LocType    
FROM mesTransferOutHeader LEFT OUTER JOIN aShops    
ON tohShopId = aShops.ShopId    
WHERE tohCancelled = 0    
AND tohTransFinished = 0  and tohType='TO'  

UNION ALL

SELECT 'Inter Division Sales', tohId, tohNo, tohDate, tohShopId,    
ShopName, tohDepartmentid, 'S' LocType    
FROM mesTransferOutHeader LEFT OUTER JOIN aShops    
ON tohShopId = aShops.ShopId    
WHERE tohCancelled = 0    
AND tohTransFinished = 0  and tohType='IS' 

--Ref.No:1-------------------------------END-----------------------------------------------
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_030
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO



/****** Object:  View [dbo].[vwUnPostedShopTransactions]    Script Date: 03/24/2012 17:23:17 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwUnPostedShopTransactions]'))
DROP VIEW [dbo].[vwUnPostedShopTransactions]
GO


/****** Object:  View [dbo].[vwUnPostedShopTransactions]    Script Date: 03/24/2012 17:23:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- ==================================================================       
-- Created by : MANUNADH. U    
-- Created on : 23/03/2012
-- Comments   : To create a report for showing unposted shop transactions
-- =================================================================       
create VIEW [dbo].[vwUnPostedShopTransactions] AS  
SELECT 'POS' TransactionType,poshbillid TransactionId,poshbillno TransactionNo,poshbilldate TransactionDate,
	poshDepartmentid Departmentid,ph.poshshopid LocationId,S.ShopName LocationName
FROM losposheader ph 
	LEFT OUTER JOIN Ashops S ON ph.poshshopid = S.ShopID            
WHERE ph.poshcancellED = 0 and ph.poshpostED = 0 

UNION ALL
SELECT 'Goods Return Note',grnh.grnhGoodsReturnNoteID,grnhGoodsReturnNoteNo,grnhGoodsReturnNoteDate,           
	grnhDepartmentId,grnh.grnhShopid,S.ShopName
FROM LOsGoodsReturnNoteHeader grnh           
	LEFT OUTER JOIN Ashops S ON grnh.grnhShopid = S.ShopID
WHERE  grnhPosted = 0 and grnhCancel = 0    

UNION ALL
SELECT 'Goods Exchange',sehExchangeId,sehExchangeNo,sehExchangeDate,sehDepartmentID,sehShopID,S.ShopName
FROM losposExchangeHeader               
	LEFT OUTER JOIN Ashops S ON sehShopID = S.ShopID
WHERE sehcancelled = 0 and sehposted = 0 

UNION ALL
SELECT 'Invoice',ihInvoiceId,ihinvoiceno,ihinvoicedate,ihdepartmentid,ihShopID,S.ShopName
FROM losinvoiceheader I
	LEFT OUTER JOIN Ashops S ON I.ihShopID = S.ShopID              
WHERE ihcancelled =0 and ihposted =0 and ihproforma = 0 and ihcashinvoice =0 and ihtype ='i'           

UNION ALL
SELECT 'Service Invoice',aiInvoiceID,aiInvoiceNo,aiInvoiceDate,aiDepartmentID,aiShopID,S.ShopName
FROM losAccountsInvoiceHeader 
	LEFT OUTER JOIN Ashops S ON aiShopID = S.ShopID              
WHERE aiCancelled = 0 and aiPosted = 0 and aiProforma = 0  

UNION ALL

SELECT 'Direct Invoice', ihinvoiceId, ihinvoiceno, ihinvoicedate,ihdepartmentId,IhShopID,S.ShopName
FROM losSpecialInvoiceHeader               
	LEFT OUTER JOIN Ashops S ON IhShopID = S.ShopID              
WHERE ihcancelled = 0 and ihtransfinished = 1 and ihposted = 0 and ihproforma = 0

UNION ALL

SELECT 'Payments', phPaymentID, phpaymentno, phpaymentdate,phDepartmentID,phShopID,S.ShopName 
FROM LOsPaymentVoucherHeader 
	LEFT OUTER JOIN Ashops S ON phShopID = S.ShopID
WHERE phpostED =0 and phcancellED =0 

UNION ALL
SELECT 'Local Purchase',lphbillid,lphbillno,lphBillDate,lphdepartmentid,lphShopID,S.ShopName                            
FROM losLocalPurchaseHeader            
	LEFT OUTER JOIN Ashops S ON lphShopID = S.ShopID                  
WHERE lphcancellED = 0 and lphpostED = 0 and lphConfirmed=1 

UNION ALL
SELECT 'Goods Arrival To Shop',gahArrivalID,gahArrivalNo, gahArrivalDate, gahdepartmentid,gahShopid,S.ShopName
FROM  LosGoodsArrivaltoShopHeader ga       
	LEFT OUTER JOIN Ashops S ON gahShopid = S.ShopID  
WHERE  gahCancelled = 0 and gahposted = 0 and gahTransFinished = 1       

UNION ALL
SELECT 'Transfer In',TIHID,TIHNO,TIHDate,tihdepartmentid,TIHShopid,S.ShopName
FROM LOSTransferinheader tinh  
	LEFT OUTER JOIN Ashops S ON TIHShopid = S.ShopID  
WHERE  TIHcancel =0 and TIHPosted =0 and TIHTransFinished = 1 and TIHType = 'TI'    

UNION ALL
SELECT 'Transfer Out',ToHID, ToHNO, ToHDate,tohdepartmentid ,TOHShopid,S.ShopName
FROM mestransferoutheader tinh     
	LEFT OUTER JOIN Ashops S ON TOHShopid = S.ShopID  
WHERE  ToHcancelled =0 and ToHPosted =0 and ToHTransFinished = 1 and tohtype ='TO'    

UNION ALL

SELECT 'Despatch To Godown',dgHID,dgHNO,dgHDate,dghdepartmentid,dghShopID,S.ShopName
FROM mesDespatchToGodownHeader tinh   
	LEFT OUTER JOIN Ashops S ON dghShopID = S.ShopID  
WHERE  dgHcancelled = 0 and dgHPosted = 0 and dgHTransFinished = 1   

UNION ALL
SELECT 'Reexport',rehExportId,rehExportNo,rehExportDate,rehdepartmentid,rehShopID,S.ShopName
FROM losExportHeader   
	LEFT OUTER JOIN Ashops S ON rehShopID = S.ShopID  
WHERE rehcancelled =0 and rehposted =0 and rehcashinvoice =0 and rehtype ='i'   

UNION ALL

SELECT 'Inhouse Consumption',whID, whno, whdate,whdepartmentid,whShopID,S.ShopName                   
FROM loswriteoffheader 
	LEFT OUTER JOIN Ashops S ON whShopID = S.ShopID  
WHERE WhCancelled =0 and whposted =0 and whtype='I' and whVerified=1                    

UNION ALL
SELECT 'Inhouse Return',IHRHID,IHRHNo,IHRHDate,IHRHdepartmentid,IHRHShopID,S.ShopName   
FROM LOs_InHouseCons_ReturnHeader 
	LEFT OUTER JOIN Ashops S ON IHRHShopID = S.ShopID 
WHERE IHRHCancelled =0 and IHRHposted=0 and IHRHConfirmed=1                      
  
UNION ALL
SELECT 'Stock Write Off Shop',whId,whno,whdate,whdepartmentId,whShopID,S.ShopName
FROM loswriteoffheader   
	LEFT OUTER JOIN Ashops S ON whShopID = S.ShopID 
WHERE whcancellED =0 AND whposted =0 and whType='W'  

UNION ALL

SELECT 'Stock Verification Shop',svhId, svhno, svhdate,svhdepartmentId,svhShopId,S.ShopName
FROM losstockverificationheader   
	LEFT OUTER JOIN Ashops S ON svhShopId = S.ShopID 
WHERE svhcancelled =0 and svhposted =0   

--UNION ALL 
--SELECT 'Recovery Shop',srId,srtransno,srdate,srDepartmentId,srShopID,S.ShopName
--FROM losStockRecovery r
--	LEFT OUTER JOIN Ashops S ON R.srShopID = S.ShopID 
--WHERE srposted =0     

UNION ALL
SELECT 'Booking Advance',serbookhid,serbookhinspectionno,serbookhInspectionDate,serbookhdepartmentid,
	serbookhshopid,S.ShopName
FROM losservicebookingheader bk
	LEFT OUTER JOIN Ashops S ON serbookhshopid = S.ShopID
WHERE serbookhinpcancelled = 0 and serbookhposted = 0 and serbookadvanceamount > 0 and serbookhstatus <>'n'  

UNION ALL
SELECT 'Booking Invoice',li.serinvhid,li.serinvno,li.serinvhdate,li.serinvhdepartmentid,li.serinvhshopid,S.ShopName        
FROM losserviceinvheader li                     
	LEFT OUTER JOIN Ashops S ON li.serinvhshopid = S.ShopID         
WHERE li.serinvhcancelled =0 AND li.serinvhposted =0 

UNION ALL
SELECT 'Booking Cancellation',bkcancellId,bkcancellno,bkcancelldate,0,bkcancellshopid,S.ShopName
from losbookingcancellation 
	LEFT OUTER JOIN Ashops S ON bkcancellshopid = S.ShopID     
where bkcancellId = 0 and  bkcancellcancelled=0 AND bkcancellposted=0 
 
UNION ALL 
SELECT 'Inter Department Sales',ToHID,ToHNO,ToHDate,tohdepartmentid,ToHShopid,S.ShopName  
FROM mestransferoutheader tinh   
	LEFT OUTER JOIN Ashops S ON ToHShopid = S.ShopID     
WHERE  ToHcancelled =0 AND ToHPosted =0 AND ToHTransFinished = 1 AND tohType ='IS'     

UNION ALL 
SELECT 'Inter Department Purchase',TIHID,TIHNO,TIHDate,tihdepartmentid,TIHShopid,S.ShopName 
FROM LOSTransferinheader tinh   
	LEFT OUTER JOIN Ashops S ON TIHShopid = S.ShopID 
WHERE  TIHcancel =0 and TIHPosted =0 and TIHTransFinished = 1 and TIHType = 'IP'  

UNION ALL

SELECT 'Shop Debit/Credit Note',losDCNId,losDCNNo,losDCNDate,losdcndepartmentid,losDCNShopid,S.ShopName
from losDebitCreditNote  
	LEFT OUTER JOIN Ashops S ON losDCNShopid = S.ShopID    
where losDCNPosted = 0 and losDCNCancelled = 0 
  
UNION ALL 
SELECT ' Agreement',mghAgreementID, mghAgreementNo,mghAgreementDate,mghDepartmentid, mghShopId,S.ShopName
FROM losApartmentAgreementHeader ah  
	LEFT OUTER JOIN Ashops S ON mghShopId = S.ShopID
WHERE mghCancelled = 0 and mghPosted = 0 and mghadvdate is not null  

UNION ALL
SELECT 'Utility Bill Details',tbhBillId,tbhBillNo,tbhBillDate,tbhDepartmentID,tbhShopId,S.ShopName
from losTenantServiceBillHeader 
	LEFT OUTER JOIN Ashops S ON tbhShopId = S.ShopID
where tbhPosted=0 and tbhCancelled=0 

UNION ALL
SELECT 'Room Billing',abhBillId ,abhBillNo,abhBillDate,abhDepartmentid,abhSHopID,S.ShopName
FROM losApartmentBillHeader  
	LEFT OUTER JOIN Ashops S ON abhSHopID = S.ShopID
WHERE abhPosted=0 and abhCancelled=0  
   
UNION ALL   
SELECT 'Check Out Returns',chID,chNo,chDate,ChDepartmentID,chShopID,S.ShopName
FROM losApartmentCheckOut   
	LEFT OUTER JOIN Ashops S ON chShopID = S.ShopID
WHERE chCancelled = 0 and chPosted = 0 and (chDepositAmount>0 or chAvaliedAmount>0)  

UNION ALL
SELECT 'HP Invoices',hpqhQuotationID,hpqhQuotationNo,hpqhQuotationDate,0, hpqhShopId, S.ShopName         
FROM loshpinvoiceheader     
	LEFT OUTER JOIN Ashops S ON hpqhShopId = S.ShopID        
WHERE hpqhcancel =0 and hpqhposted =0  and hpqhConfirmed=1 and hpqhType='I'  

UNION ALL             
SELECT 'HP Shop Receipts',hprhReceiptID,hprhReceiptNo,hprhReceiptDate,0,hprhShopID,S.ShopName
FROM loshpReceiptheader         
	LEFT OUTER JOIN Ashops S ON hprhShopID = S.ShopID  
WHERE hprhCancel=0 and hprhPosted=0 and hprhReceiptType='S' 

UNION ALL
SELECT 'HP Shop Down Payment',hprhReceiptID,hprhReceiptNo,hprhReceiptDate,0,hprhShopID,S.ShopName
FROM loshpReceiptheader     
	LEFT OUTER JOIN Ashops S ON hprhShopID = S.ShopID  
WHERE hprhCancel=0 and hprhPosted=0 and hprhReceiptType='A' 

UNION ALL
SELECT 'HP Resale',hphResaleID,hphResaleNo,hphReSaleDate,0,hphShopID,S.ShopName
FROM  losHpReSaleHeader       
	LEFT OUTER JOIN Ashops S ON hphShopID = S.ShopID 
WHERE hphCancel =0 and hphposted =0  

UNION ALL
SELECT 'HP Repossession',hprhRepossessionID,hprhRepossessionNo,hprhRepossessionDate,0,hprhShopId,S.ShopName
FROM losHpRepossessionHeader     
	LEFT OUTER JOIN Ashops S ON hprhShopId = S.ShopID 
WHERE hprhCancel =0 and hprhposted =0  

UNION ALL
SELECT 'Shop Purchase Return',whID,whNo,whDate,whDepartmentId,whShopId,S.ShopName
FROM losPurchaseReturnHeader 
	LEFT OUTER JOIN Ashops S ON whShopID = S.ShopID 
WHERE whCancelled = 0 And whPosted = 0 And whType ='P'  
  
UNION ALL
SELECT 'Food and Beverages Bill',poshBillID,poshBillNo,poshBillDate,poshDepartmentid,poshShopID,S.ShopName
FROM losPosFandBHeader h    
	LEFT OUTER JOIN Ashops S ON poshShopID = S.ShopID     
WHERE h.poshCancelled=0 and h.poshPosted = 0 

UNION ALL
SELECT 'Goods Arrival Inventory',ahArrivalId,ahArrivalNo,ahArrivalDate,ahdepartmentid,
	CASE WHEN (ahShopID IS NULL AND AHGodownID IS NULL) THEN 0 
		WHEN ahShopID IS NULL THEN AHGodownID ELSE ahShopID END, 
	CASE WHEN (ahShopID IS NULL AND AHGodownID IS NULL) THEN 'HQ' 
		WHEN ahShopID IS NULL THEN G.GodownName ELSE S.ShopName END	
FROM LOiArrivalHeader ga     
	LEFT OUTER JOIN Ashops S ON ahShopID = S.ShopID 
	LEFT OUTER JOIN aGodown G ON G.GodownID=AHGodownID
WHERE ahCancelled = 0 and ahPosted = 0 and ahTransFinished = 1     

UNION ALL
SELECT 'Goods Dispatch to Shop',dhDespatchId, dhdespatchno, dhdespatchdate,dhDepartmentId,dhShopID,S.ShopName
FROM meiDespatchToShopHeader     
	LEFT OUTER JOIN Ashops S ON dhShopID = S.ShopID 
WHERE dhCancelled = 0 and dhPosted =0 and dhTransFinished=1

UNION ALL
SELECT 'Stock Write off Inventory',whID, whno, whdate,whdepartmentid,whGodownID,G.GodownName
FROM loiwriteoffheader           
	LEFT OUTER JOIN aGodown G ON G.GodownID=whGodownID
WHERE whcancellED = 0 and whposted = 0 and whType = 'W'          
  
UNION ALL  
SELECT 'Stock Verification Inventory',svhid,svhno,svhdate,svhdepartmentid,svhGodownid,G.GodownName
FROM loiStockVerificationHeader   
	LEFT OUTER JOIN aGodown G ON G.GodownID=svhGodownid
WHERE svhcancelled =0 and svhposted =0   

UNION ALL
SELECT 'Recovery Inventory',srID,srtransno,srDate,0,srGodownID,G.GodownName
FROM loiStockRecovery i
	LEFT OUTER JOIN aGodown G ON G.GodownID=srGodownID
WHERE srposted = 0   

UNION ALL
SELECT 'Special Despatch',dhDespatchId, dhdespatchno, dhdespatchdate,dhDepartmentId,dhgodownid,G.GodownName
FROM meiSpecialDespatchToShopHeader 
	LEFT OUTER JOIN aGodown G ON G.GodownID=dhgodownid
WHERE dhCancelled = 0 and dhposted = 0     

UNION ALL
SELECT 'Godown to Godown Transfer',gthDespatchID,gthDespatchNo,gthDespatchDate,gthDepartmentId,gthFromGodownId,
	G.GodownName
FROM MEiGodownTransferHeader tinh 
	LEFT OUTER JOIN aGodown G ON G.GodownID=gthFromGodownId  
WHERE gthCancelled = 0 and gthPosted = 0 and gthTransFinished = 1   

UNION ALL
SELECT 'Asset Transfer',whID, whno, whdate,whDepartmentId,whGodownID,G.GodownName
FROM loiWriteOffHeader   
	LEFT OUTER JOIN aGodown G ON G.GodownID=whGodownID
WHERE whCancelled = 0 and whPosted = 0  and whType ='A'  

UNION ALL
SELECT 'Purchase Return',whID, whNo, whDate,whDepartmentId,whGodownId,G.GodownName
FROM loiWriteOffHeader 
	LEFT OUTER JOIN aGodown G ON G.GodownID=whGodownID
WHERE whCancelled = 0 and whPosted = 0 and whType ='R'  

UNION ALL
SELECT 'HQ Stock Write Off',swID,swTransCode,swDate,0, 
	CASE WHEN swShopID IS NULL THEN swGodownID ELSE swShopID END ,
	CASE WHEN swShopID IS NULL THEN G.GodownName ELSE S.ShopName  END
FROM moStockWriteOffHQ 
	LEFT OUTER JOIN Ashops S ON swShopID = S.ShopID 
	LEFT OUTER JOIN aGodown G ON G.GodownID=swGodownID
WHERE swposted =0   

UNION ALL
SELECT 'Business Promotion',wchID,wchNo,wchDate,0,wchSHOPID,S.ShopName    
FROM losWarrentyClaimHeader      
	LEFT OUTER JOIN Ashops S ON wchSHOPID = S.ShopID
    WHERE wchType='BP' and wchposted=0 and wchCancelled=0 and wchConfirmed=1 

UNION ALL
SELECT 'Warrenty Claim',wchID,wchNo,wchDate,0,wchShopID,S.ShopName
FROM losWarrentyClaimHeader
	LEFT OUTER JOIN Ashops S ON wchSHOPID = S.ShopID
WHERE wchType='WC' and wchposted=0 and wchCancelled=0 and wchConfirmed=1 


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_035
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = N'dbo' AND TABLE_NAME = N'vwPaymentsOnPO' 
)   DROP VIEW dbo.vwPaymentsOnPO
GO
/*
CREATED BY :SHINE
CREATED ON : 24.03.2012
PURPOSE	   : To select Payments Against a Purchase Order
*/
CREATE VIEW vwPaymentsOnPO AS
select pvdd.pddhqpoid POID,phPaymentNo,pvh.phexchangerate from aHQpaymentvoucherheader pvh 
INNER JOIN aHQPaymentVoucherDebitDetails pvdd on pvh.phPaymentID = pvdd.pddPaymentID where  
pvh.phcancelled=0 and pvh.phpohid IS NULL 

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_178
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = N'dbo' AND TABLE_NAME = N'vwCreditInvoice_BillWise' 
)   DROP VIEW dbo.vwCreditInvoice_BillWise
GO
Create  view vwCreditInvoice_BillWise as   
---Created by :Jyothish.SR
--- Date :12.04.2012
--- CreditInvoice-BillWise Report
select lh.ihShopID,ihInvoiceID,ihInvoiceNo,ihInvoiceDate,CustomerName,ihCustomerID,ItemDescription,PackingTypeName,idPQuantity,idQuantity   
,idUnitPrice,lphBillID, lphBillNo,lphBillDate,VendorName,lpdItemQuantity,lpdItemUnitPrice from losInvoiceheader lh ,losInvoiceDetail lt   
,LosLocalPurchaseHeader dh , LosLocalPurchaseDetail dt ,acustomermaster c ,aVendorMaster v ,aitem it ,aPackingType p where  lh.ihShopID=lt.idShopID   
and ihCancelled=0 and ihType='I' and dh.lphBillID=dt.lpdBillID and lt.idBillID is not null and dh.lphBillID=dt.lpdBillID and dh.lphCancelled=0  
and lt.idBillID=dh.lphBillID and lh.ihInvoiceID=lt.idInvoiceID and dh.lphShopID=dt.lpdShopID and lt.idItemID=dt.lpdItemID  
and c.CustomerID=ihCustomerID   and v.VendorID=lphVendorID and it.ItemID=idItemID and p.PackingTypeID=idPackingTypeID  
  

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

/****** Object:  View [dbo].[vwPurchaseBillDetailwithunit]    Script Date: 05/09/2012 11:51:08 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwPurchaseBillDetailwithunit]'))
DROP VIEW [dbo].[vwPurchaseBillDetailwithunit]
GO

USE [adminv2]
GO

/****** Object:  View [dbo].[vwPurchaseBillDetailwithunit]    Script Date: 05/09/2012 11:51:09 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

 /****** Object:  View dbo.vwPurchaseBillDetailwithunit    Script Date: 18/01/2003 9:45:36 PM ******/    
--Last Modified on  : 12/12/02    
--Modified by  : leo    
--Comments  : v3    
--Modified On : 17/06/2006   
--modified By : aneesh [removed text in convert function and added varchar]  
------------------------------------------------------------------------------
-- RefNo		 : RefNo-1
-- Modified By   : MANUNADH.U
-- Modified Date : 09-05-2012
-- Comment       : Added PackingTypeName to show in the rptpurchasebill.rpt                
------------------------------------------------------------------------------  
CREATE view [dbo].[vwPurchaseBillDetailwithunit]    
as select pb.*,u.unitcode,u.unitname, p.packingtypecode,p.PackingTypeName,convert(varchar(250),vw.itemdescription)     
itemdescription 
from LOspPurchaseBillDetail pb 
	left outer join aitem ai on pbdItemID=ItemID,  
	apackingtype p, aunit u, vwitemdescription vw    
where p.packingtypeid= pb.pbdpackingtypeid and ai.unitsid = u.unitid and ai.itemid= vw.itemid    


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_129
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE ADMINV2;
GO
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = N'dbo' AND TABLE_NAME = N'vwPopulateGodownArrivals' 
)   DROP VIEW dbo.vwPopulateGodownArrivals
GO
/*
CREATED BY : SHINE DAS
CREATED ON : 11.05.2012
Purpose	   : To populate godown arrival details in Cancel posting.
*/
CREATE VIEW vwPopulateGodownArrivals AS

select ah.ahArrivalID ArrivalID, ahArrivalNo ArrivalNo, ahArrivalDate ArrivalDate,
cast(cast(sum(si.adDespatchedQty) as decimal(18,2)) as varchar(20)) DespatchedQty,
cast(cast(sum(si.adReceivedQty) as decimal(18,2)) as varchar(20)) ReceivedQty, 
ahdepartmentid departmentid,ahLocalGodownId GodownId 
from loiArrivalHeader AH, loiarrivaldetail si where
ahCancelled = 0 and ahposted=1 and  ah.ahlocalGodownId=si.adGodownId 
and ah.aharrivalid=si.adarrivalid 
group by ahArrivalID,ahArrivalNo,ahArrivalDate,ahdepartmentid,ahlocalGodownId  

union all

select ah.ahArrivalID ArrivalID, ahArrivalNo ArrivalNo, ahArrivalDate ArrivalDate,
cast(cast(sum(si.asdDespatchedGoodQty) as decimal(18,2)) as varchar(20)) DespatchedQty,
cast(cast(sum(si.asdReceivedGoodQty) as decimal(18,2)) as varchar(20)) ReceivedQty, 
ahdepartmentid departmentid, ahLocalGodownId GodownId
from loiArrivalHeader AH, loiarrivalshipmentdetail si where
ahCancelled = 0 and ahposted=1 and ah.ahlocalGodownId=si.asdGodownID 
and ah.aharrivalid=si.asdArrivalID  
group by ahArrivalID,ahArrivalNo,ahArrivalDate,ahdepartmentid,ahlocalGodownId    
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

/****** Object:  View [dbo].[vwshopSalesAccountWise]    Script Date: 05/14/2012 14:40:01 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwshopSalesAccountWise]'))
DROP VIEW [dbo].[vwshopSalesAccountWise]
GO

USE [adminv2]
GO

/****** Object:  View [dbo].[vwshopSalesAccountWise]    Script Date: 05/14/2012 14:40:02 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- Created By : Benzigar S D  
-- Created On : 29-11-2008  
---------------------------------------------------------------------------------------------------      
--<<Ref-01>>          
--Modified ON :- 14/05/2012              
--Modified By :- MANUNADH.U          
--Comment     :- Correct the calculation of TotalDiscount and Discper after GST implementation (To show 
--				 in the rptshopsalesaccountwise.rpt - P&C-Sales Report - Shop Sales Account wise)
---------------------------------------------------------------------------------------------------              
CREATE VIEW [dbo].[vwshopSalesAccountWise] AS     
--pos         
select poshBillId, poshShopId, poshBillDate, poshBillNo, posditemid,code,itemdescription,posdpquantity,
posdunitprice totalamount,posdunitprice/posdpquantity unitprice,posdactualunitprice,posdcostprice,  
--<<Ref-01>>  
--(posdactualunitprice*posdpquantity)- posdunitprice TotalDiscount,  
--(((posdactualunitprice*posdpquantity)- posdunitprice)/(posdactualunitprice*posdpquantity))*100 Discper,
case when (posdactualunitprice * posdpquantity) < (posdunitprice - posdItemTaxAmount ) then 0
else (posdactualunitprice * posdpquantity) - (posdunitprice - posdItemTaxAmount) end as TotalDiscount
,case when (posdactualunitprice * posdpquantity) < (posdunitprice - posdItemTaxAmount ) then 0
else (((posdactualunitprice * posdpquantity) - (posdunitprice - posdItemTaxAmount)) /(posdactualunitprice* posdpquantity) )* 100 end as Discper,
--<<Ref-01>>             
poshcancelledremarks Remarks,poshCustomerName, AccountDesc          
from losposheader, aAccountMaster,losposdetail,vwitemdescription         
where poshcancelled = 0        
and poshCashAccid = accountid         
and poshCompanyID = CompanyId  
and poshBillId=posdbillid  
and poshShopId=posdshopid   
and itemid=posditemid  
  
Union all  
  
--credit invoice        
select ihinvoiceid, ihShopId,ihinvoicedate,ihinvoiceno,iditemid,  
code,itemdescription,  
idPQuantity,idunitprice totalamount,idunitprice/idPQuantity unitprice,idActualUnitPrice,idcostprice,  
(idactualunitprice*idpquantity)- idunitprice TotalDiscount,   
case when idactualunitprice*idpquantity<> 0 then(((idactualunitprice*idpquantity)- idunitprice)/(idactualunitprice*idpquantity))*100  end Disper,            
ihremarks remarks,CustomerName, 'Credit Invoice' AccountDesc         
from losinvoiceheader, acustomermaster,losinvoicedetail,vwitemdescription         
where ihcancelled = 0        
and ihcustomerid = customerid         
and ihproforma = 0         
and ihtype = 'i'     
and ihinvoiceid=idinvoiceid  
and ihshopid=idshopid     
and itemid=iditemid    
  
Union all  
   
  --exchange        
select sehexchangeid, sehShopId, sehexchangedate, sehExchangeno,seditemid,  
code,itemdescription,sedPQuantity,sedunitprice totalamount,  
sedunitprice/sedPQuantity unitprice, sedActualUnitPrice,sedcostprice,  
(sedactualunitprice*sedpquantity)- sedunitprice TotalDiscount,  
 case when sedactualunitprice*sedpquantity<> 0 then(((sedactualunitprice*sedpquantity)- sedunitprice)/(sedactualunitprice*sedpquantity))*100  end Disper,                        
sehremarks remarks, h.sehExchangerName, AccountDesc         
from losposexchangeheader h, aAccountMaster a,losposexchangedetail e,vwitemdescription        
where sehcancelled = 0         
and sehCashAccID = a.accountid         
and sehCompanyId = a.CompanyId   
and sehexchangeid=sedexchangeid  
and sedBillorExchange='E'  
and itemid=seditemid    


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

/****** Object:  View [dbo].[vwItemsoldCustomerwise]    Script Date: 05/14/2012 17:43:41 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwItemsoldCustomerwise]'))
DROP VIEW [dbo].[vwItemsoldCustomerwise]
GO

USE [adminv2]
GO

/****** Object:  View [dbo].[vwItemsoldCustomerwise]    Script Date: 05/14/2012 17:43:41 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--<<Ref-01>>          
--Modified ON :- 14/05/2012              
--Modified By :- MANUNADH.U          
--Comment     :- Customer - Item Sold History Report (P&C - Inventory Reports)
--				 doesnot show data for a purticular customer for the corresponding department
--				 (DepartmentId Is joined incorrectly with shopid ).
CREATE VIEW [dbo].[vwItemsoldCustomerwise] AS       
SELECT VW.posdItemId ItemId,itemcode,itemdescription,VW.poshShopId ShopId,VW.posdQuantity Qty,
	VW.posdUnitPrice SoldRate,dUnitPrice dSoldRate, cUnitPrice cSoldRate,VW.poshBillDate SoldDate,VW.poshBillNo RefNo,
	a.ItemCategoryId,CostPrice,dCostPrice, cCostPrice,Amount, dAmount, cAmount,apt.Packingtypename PackingType,
	Customername,CustomerID,adp.departmentid Departmentid,
	case posdUnitPrice when 0 then 0 else (posdUnitPrice-costprice)/posdUnitPrice*100 end margin       
FROM vwShopItemSalesWithCustomerAndPack vw, aItem a, aItemcategory b, apackingtype apt,ashops S,adepartmentmaster adp       
WHERE VW.posdItemId = a.ItemId AND a.ItemCategoryId = b.ItemCategoryId and apt.packingtypeid=vw.packingtypeid   
	--AND vw.poshShopId=adp.departmentid   --<<Ref-01>>  Comment the Previous code
	AND VW.poshShopId=S.SHOPID AND S.departmentid =adp.departmentid 
  
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

/****** Object:  View [dbo].[vwSpecialInvoiceReturn]    Script Date: 09/21/2011 13:03:59 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwSpecialInvoiceReturn]'))
DROP VIEW [dbo].[vwSpecialInvoiceReturn]
GO

USE [adminv2]
GO

/****** Object:  View [dbo].[vwSpecialInvoiceReturn]    Script Date: 09/21/2011 13:03:59 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

    
-- Modified on : 29/07/2003                    
-- Modified by : Kishore                    
-- Comments    : Replace with script from v2                    
-----------------------------------------------------------                    
-- Modified on : 14/10/2003                    
-- Modified by : Kishore                    
-- Comments    : Added idFreeQuantity column                    
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
         
--modified by 181203 venki specialinvoice filteration                    
--Verified by      : Hariharan                     
--Verified Date     : 04/05/2004 (verified From Dev Server(Fies))                
              
--Modified by :Benzigar S D              
--Action :  sum(idUnitPrice)              
--Purpose :  To show the total price in case of multiple godown              
            
--Modified by :Abhishek CS              
--Action :  Add sales person and change view by using joins in case sales person name is null            
          
--Modified By : Yogesh Joe 14-07-2010          
--Action : Added the column idGodownID. It was missing.          
--     'rptSpecialInvReturn_Multi.rpt' and 'rptSpecialInvReturnwoutdisc_Multi.rpt' need it.        
        
--Modified by :Abhishek CS on 12-10-10              
--Action :  Add cancelled remarks for modified addree showing in SInvoice report            
-----------------------------------------------------------------------------    
--Modified by :Nidheesh P V    
--Modified on :20/07/2011    
--Action :  Included Exchange Rates & currency id in select statement.    
--Modified Area: In Spl Invoice Reports.    
--Reference No :RefNo-1           
-----------------------------------------------------------------------------    
--Modified by :SHINE   
--Modified on :16/09/2011    
--Action :  ADDE NEW FIELDS FOR WARRANTY FEATURE  
--Modified Area: In Spl Invoice Reports.    
--Reference No :RefNo-2     
-----------------------------------------------------------------------------   
--Modified by :MANUNADH.U   
--Modified on :21/09/2011    
--Action :  ADD NEW CONDITION TO FILTER SPL INVOICE CASH AND CREDIT TRANSACTIONS TO AVOID DUPLICATE 
--			DATA  
--Modified Area: In Spl Invoice Reports.    
--Reference No :RefNo-3     
-----------------------------------------------------------------------------         
--Modified by  :AADYAKUMAR.D.V        
--Modified on  :01/06/2012          
--Action       : For distributing Discount,to show discount in special invoice godown wise report
--Modified Area: In Spl Invoice Reports.  
--Ticket id    :VXM-317988        
--Reference No :RefNo-4          
-----------------------------------------------------------------------------   

CREATE view [dbo].[vwSpecialInvoiceReturn] AS      
----Special Invoice - Cash                      
  select vw.ItemDescription,ihInvoiceId,ihInvoiceNo,ihShopId,ihInvoiceDate,idItemId,
	sum(idQuantity)idQuantity,sum(ReqQty)ReqQty,sum(idpQuantity)idpQuantity,sum(idUnitPrice)idUnitPrice,
	idActualUnitPrice,idCostPrice,ihRecAddUser,ihRecModifyUser,UnitName,PackingTypeName,CustomerName,
	customerid,Symbol,ihDiscount,ihRemarks,idRateType,ihCashInvoice,ihReferenceNo,ihDueDate,
	IhCancelledRemarks,IhCancelled,Address1,Address2,Address3,u.UnitCode,idFreeQuantity,ItemCode,
	ihsalespersonid,Spername,idGodownID,ihexchangerates,ac.currencyid,  --RefNo-1                        
	dbo.fnIssueSerialNosForSpINV(5023,idGodownID,ihInvoiceId,idItemId) idSerialNo,idServWarrantyUpto,
	idPartsWarrantyUpto,---RefNo-2
    idItemTaxAmount ,IhInvoiceAmount,idItemTaxPercentage,   
    (idActualUnitPrice*idpQuantity)*(ihdiscount/100) dis --RefNo-4     
from losspecialinvoiceheader             
	left outer join losspecialinvoicedetail on ihShopid = idshopid and ihinvoiceid = idinvoiceid             
	left outer join aitem a on iditemid = a.itemid            
	left outer join apackingtype p on idpackingtypeid = p.packingtypeid            
	left outer join vwitemdescription vw on a.itemid = vw.itemid            
	left outer join aunit u on u.unitid = a.unitsid             
	left outer join acustomermaster ac on ac.customerid = ihcustomerid             
	left outer join acurrencymaster c on ac.currencyid = c.currencyid             
	left outer join asalespersonmaster sp on sp.Sperid=losspecialinvoiceheader.ihsalespersonid            
	left outer join aShopsalespersondetails sd on sp.Sperid=sd.SperID and sd.SperShopid=losspecialinvoiceheader.IhShopID               
where IhCashInvoice=1			--<<RefNo-3>> 
group by vw.ItemDescription,ihInvoiceId,ihInvoiceNo,ihShopId,ihInvoiceDate,idItemId,idActualUnitPrice, 
	idCostPrice,ihRecAddUser,ihRecModifyUser,UnitName,PackingTypeName,CustomerName,customerid,Symbol,
	ihDiscount,ihRemarks,idRateType,ihCashInvoice,ihReferenceNo,ihDueDate,IhCancelledRemarks,IhCancelled,
	Address1,Address2,Address3,u.UnitCode,idFreeQuantity,ItemCode,ihsalespersonid,Spername,idGodownID,    
	ihexchangerates,ac.currencyid,idSerialNo,idServWarrantyUpto,idPartsWarrantyUpto,
	idItemTaxAmount ,IhInvoiceAmount,idItemTaxPercentage ,idUnitPrice,idpQuantity --RefNo-4   
UNION ALL
----Special Invoice - Credit  
  select vw.ItemDescription,ihInvoiceId,ihInvoiceNo,ihShopId,ihInvoiceDate,idItemId,sum(idQuantity)idQuantity, 
	sum(ReqQty)ReqQty,sum(idpQuantity)idpQuantity,sum(idUnitPrice) idUnitPrice,idActualUnitPrice,
	idCostPrice,ihRecAddUser,ihRecModifyUser,UnitName,PackingTypeName,CustomerName,customerid,Symbol,
	ihDiscount,ihRemarks,idRateType,ihCashInvoice,ihReferenceNo,ihDueDate,IhCancelledRemarks,IhCancelled,                      
	Address1,Address2,Address3,u.UnitCode,idFreeQuantity,ItemCode,ihsalespersonid,Spername,idGodownID,
	ihexchangerates,ac.currencyid,  --RefNo-1                        
	dbo.fnIssueSerialNosForSpINV(5008,idGodownID,ihInvoiceId,idItemId) idSerialNo,idServWarrantyUpto,idPartsWarrantyUpto,---RefNo-2     
	idItemTaxAmount,IhInvoiceAmount,idItemTaxPercentage,  
    (idActualUnitPrice*idpQuantity)*(ihdiscount/100) dis --RefNo-4
from losspecialinvoiceheader             
	left outer join losspecialinvoicedetail on ihShopid = idshopid and ihinvoiceid = idinvoiceid             
	left outer join aitem a on iditemid = a.itemid            
	left outer join apackingtype p on idpackingtypeid = p.packingtypeid            
	left outer join vwitemdescription vw on a.itemid = vw.itemid            
	left outer join aunit u on u.unitid = a.unitsid             
	left outer join acustomermaster ac on ac.customerid = ihcustomerid             
	left outer join acurrencymaster c on ac.currencyid = c.currencyid             
	left outer join asalespersonmaster sp on sp.Sperid=losspecialinvoiceheader.ihsalespersonid            
	left outer join aShopsalespersondetails sd on sp.Sperid=sd.SperID and sd.SperShopid=losspecialinvoiceheader.IhShopID               
where IhCashInvoice=0			--<<RefNo-3>> 
group by vw.ItemDescription,ihInvoiceId,ihInvoiceNo,ihShopId,ihInvoiceDate,idItemId,idActualUnitPrice, 
idCostPrice,ihRecAddUser,ihRecModifyUser,UnitName,PackingTypeName,CustomerName,customerid,Symbol,
ihDiscount,ihRemarks,idRateType,ihCashInvoice,ihReferenceNo,ihDueDate,IhCancelledRemarks,IhCancelled,                      
Address1,Address2,Address3,u.UnitCode,idFreeQuantity,ItemCode,ihsalespersonid,Spername,idGodownID,    
ihexchangerates,ac.currencyid,idSerialNo,idServWarrantyUpto,idPartsWarrantyUpto ,
idItemTaxAmount,IhInvoiceAmount,idItemTaxPercentage,idUnitPrice,idpQuantity --RefNo-4  
GO


 
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--FINDSP
--STORED PROCEDURE CREATIONS AND ALTERATIONS

--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:IKF-161540
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

--spUpdateShopStockMerging 12, 1, 1    
-----------------------------------------------------------------      
-- Create on     : 23/08/2003      
-- Created in v3 : Kishore      
-- Comments    : This sp is called from trigger trUpdateLocalMerging (taken from v2)     
-----------------------------------------------------------------      
-- Ref No		 : Ref No1
-- Modified on   : 05/03/2012      
-- Modified By   : MANUNADH.U      
-- Comments      : Add code to arrive the Merged Item in Shop automatically.Otherwise stock will not show
--				   correctly in Item in Stock Report[Shopwise]   
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateShopStockMerging]') AND type in (N'P', N'PC'))
BEGIN
	DROP PROCEDURE spUpdateShopStockMerging
END
GO  
create PROCEDURE spUpdateShopStockMerging (@intMergeId as int, @intCompanyId as int,@intLocationId as int) AS      
Begin      
  Declare @intTemp as int,@intId as int,@strPrefix as VarChar(50),@strMaxNo as VarChar(50),@intMgdId as int,      
  @intMgdItemId as int,@numMgdCostPrice as numeric(18, 8),@intMgdDetailId as int,@numGsStock as numeric(18, 8)      
  ,@intItemCount as int,@intMergeItemId int --===========<Ref No1>
		        
  Set NoCount On      
  set @intTemp = 0 
  set @intItemCount=0   --===========<Ref No1>   
  -- select 2 cols. It is neccessary for running remotely      
  select 1, 0      
      
  -- check if main item id or detail item id exists in unprocessed quantity      
  SELECT @intTemp = COUNT(*) FROM vwQuantityUnProcessed WHERE ItemId IN (
	SELECT mghItemId FROM aHqMergingHeader WHERE mghId = @intMergeId AND mghCompanyId = @intCompanyId      
      UNION ALL      
    SELECT mgdItemId FROM aHqMergingDetails WHERE mgdId = @intMergeId AND mgdCompanyId = @intCompanyId      
  ) AND LocationId = @intLocationId AND LocationType = 'S'      
  --===========<Ref No1>
  SELECT @intMergeItemId = mghItemId FROM aHqMergingHeader WHERE mghId = @intMergeId AND mghCompanyId = @intCompanyId
  --===========<Ref No1>    
  -- item ids exist in unprocessed quantity      
  If (@intTemp > 0)      
    Begin      
	  set @intTemp = 0      
      -- check if the record already exists in header      
	  SELECT @intTemp = COUNT(*) FROM losMergeHeader WHERE lshRefMergeID = @intMergeId      
		AND lshCompanyId = @intCompanyId AND lshShopId = @intLocationId      
      
      -- record does not exist in header so just insert it      
	  If (@intTemp <= 0)      
		begin         
		  -- generate next id      
		  SELECT @intId = isnull(max(lshId), 0) + 1 FROM losMergeHeader WHERE lshShopId = @intLocationId      
			AND lshCompanyId = @intCompanyId      
		
		  -- get prefix      
		  SELECT @strPrefix = Prefix FROM aPrefix WHERE CompanyId = @intCompanyId      
			AND InterfaceId = 1910 AND ShopId = @intLocationId      
      
		  -- get max no      
		  SELECT @strMaxNo = isnull(max(convert(int, right(lshNo,len(lshNo) - len(@strPrefix)))), 0)       
		  FROM losMergeHeader WHERE lshCompanyId = @intCompanyId AND len(lshNo) > len(@strPrefix)       
			AND substring(lshNo, 1, len(@strPrefix)) = @strPrefix AND lshShopId = @intLocationId      
			AND isnumeric(isnull(right(lshNo, len(lshNo) - len(@strPrefix)), 0)) = 1       
  
		  If (@strMaxNo = '0')      
			Begin      
			  set @strMaxNo = @strPrefix + '1'          
			end      
		  else      
			begin      
			  set @strMaxNo = @strPrefix + convert(varchar, (convert(int, @strMaxNo) + 1))      
			end      
         
          -- generate next no      
          INSERT INTO losMergeHeader(lshId, lshCompanyId, lshShopId, lshNo, lshDate,lshRefMergeId, lshItemId,       
			lshTransFinished,lshCancelled, lshUpdatetime, lshQty, lshNoOfRec,rowguid)      
		  (
			SELECT @intId, @intCompanyId, @intLocationId,@strMaxNo, GetDate(),mghId, mghItemId, 0, 0, GetDate(), 
			  isnull(Stock, 0), 0 ,newID()     
			FROM aHqMergingHeader h LEFT OUTER JOIN vwInquiryShopStock s ON h.mghItemId = s.ItemId      
			  AND @intLocationId = s.ShopId      
			WHERE mghId = @intMergeId AND mghCompanyId = @intCompanyId
		  )      
		End      
	  Else -- get the merging id to insert into details      
		Begin      
		  SELECT @intId = lshId, @intLocationId = lshShopId FROM losMergeHeader 
		  WHERE lshRefMergeID = @intMergeId AND lshCompanyId = @intCompanyId AND lshShopId = @intLocationId      
		End      
	End      
  Else      
	Begin           -- if no items in unprocessed quantity      
		-- check if the record already exists in header      
	  SELECT @intTemp = COUNT(*) FROM losMergeHeader 
	  WHERE lshRefMergeID = @intMergeId AND lshCompanyId = @intCompanyId AND lshShopId = @intLocationId      
      
      -- record does not exist in header  -- so just insert it      
	  If (@intTemp <= 0)      
		Begin      
		-- generate next id      
		  SELECT @intId = isnull(max(lshId), 0) + 1 FROM losMergeHeader      
		  WHERE lshShopId = @intLocationId AND lshCompanyId = @intCompanyId      
		
		-- get prefix      
		  SELECT @strPrefix = Prefix FROM aPrefix      
		  WHERE CompanyId = @intCompanyId AND InterfaceId = 1910 AND ShopId = @intLocationId      
         
		-- get max no      
		SELECT @strMaxNo = isnull(max(convert(int, right(lshNo,len(lshNo) - len(@strPrefix)))), 0)       
		FROM losMergeHeader        
		WHERE lshCompanyId = @intCompanyId AND len(lshNo) > len(@strPrefix) AND isnumeric(isnull(right(lshNo,       
		  len(lshNo) - len(@strPrefix)), 0)) = 1 AND substring(lshNo, 1, len(@strPrefix)) = @strPrefix      
		  AND lshShopId = @intLocationId      
        
        If (@strMaxNo = '0')      
		  Begin      
			set @strMaxNo = @strPrefix + '1'          
		  End      
		Else      
		  Begin      
			set @strMaxNo = @strPrefix + convert(varchar,(convert(int, @strMaxNo) + 1))      
		  End      
      
        -- generate next no      
        INSERT INTO losMergeHeader(lshId,lshCompanyId,lshShopId,lshNo,lshDate,lshRefMergeId,lshItemId,       
		  lshTransFinished,lshCancelled, lshUpdatetime, lshQty, lshNoOfRec,rowguid)      
		(SELECT @intId, @intCompanyId, @intLocationId,@strMaxNo, GetDate(),mghId, mghItemId, 1, 0, GetDate(), 
		  isnull(Stock, 0), 0 ,newID() FROM aHqMergingHeader h 
		  LEFT OUTER JOIN vwinquiryShopStock s ON h.mghItemId = s.ItemId AND @intLocationId = s.ShopId      
		WHERE mghId = @intMergeId  AND mghCompanyId = @intCompanyId)        
	  End      
    Else -- if header exists, update trans finished      
      Begin      
		SELECT @intId = lshId, @intLocationId = lshShopId FROM losMergeHeader      
		WHERE lshRefMergeId = @intMergeId AND lshCompanyId = @intCompanyId AND lshShopId = @intLocationId      
		  
		UPDATE losMergeHeader SET lshTransFinished = 1 WHERE lshRefMergeId = @intMergeId      
		AND lshCompanyId = @intCompanyId AND lshShopId = @intLocationId      
	  End      
    -- delete records from details if they exist bcos play it safe, after all, triggers are involved      
	DELETE FROM losMergeDetails WHERE lsdId = @intId AND lsdCompanyId = @intCompanyId AND lsdShopId = @intLocationId      
	-- open the cursor      
	Declare CurShopDetails Cursor For      
	  SELECT mgdId, mgdItemId, mgdCostPrice,mgdDetailId, isnull(Stock, 0)      
	  FROM aHqMergingDetails LEFT OUTER JOIN vwinquiryShopStock ON mgdItemId = ItemId AND @intLocationId = ShopId      
	  WHERE mgdId = @intMergeId AND mgdCompanyId = @intCompanyId ORDER BY mgdDetailId      
          
	Open CurShopDetails      
      Fetch Next From CurShopDetails Into  @intMgdId, @intMgdItemId, @numMgdCostPrice, @intMgdDetailId,@numGsStock      
	  While @@Fetch_Status = 0      
		Begin      
		  INSERT INTO losMergeDetails (lsdId, lsdCompanyId, lsdShopId, lsdItemId,lsdQty, lsdDetailId,rowguid)      
		  VALUES (@intId, @intCompanyId, @intLocationId,@intMgdItemId, @numGsStock, @intMgdDetailId,newID()) 
		  --==========================================<<Ref No1>>
		  if @numGsStock > 0
		  begin
		    SELECT @intItemCount = COUNT(*) FROM aShopItemDetail 
			WHERE  ShopId = @intLocationId and ItemID=@intMergeItemId
			If (@intItemCount <= 0)  		
			begin
				insert into aShopItemDetail values(@intLocationId,@intMergeItemId,0,0,0,null,0,0,NEWID())
			end
		  end		  
		  --==========================================<<Ref No1>>
		  Fetch Next From CurShopDetails InTo @intMgdId,@intMgdItemId,@numMgdCostPrice,@intMgdDetailId,@numGsStock            
		End      
    close CurShopDetails      
	Deallocate CurShopDetails      
        
	-- update no. of records      
	UPDATE losMergeHeader SET lshNoOfRec = (SELECT COUNT(*) FROM losMergeDetails      
    WHERE lsdId = @intId AND lsdCompanyId = @intCompanyId AND lsdShopId = @intLocationId)      
    WHERE lshId = @intId AND lshCompanyId = @intCompanyId AND lshShopId = @intLocationId      
       
	-- now updat the stock      
	Execute spUpdateShopItemMerge @intId, @intLocationId, @intCompanyId, 'f'      
      
	-- now updat the location stock      
	Execute spUpdateShopLocationItemMerge @intId, @intLocationId, @intCompanyId--, 'f'      
  End      
  set nocount off      
End  
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:IKF-161540
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

-- Create on   : 23/08/2003      
-- Create by   : Kishore      
-- Comments    : This sp is called from trigger trUpdateLocalMerging (taken from v2) 
----------------------------------------------------------------------------------------------------------------------
-- Ref No	   : Ref No1
-- Modified on : 05/03/2012      
-- Modified By : MANUNADH.U      
-- Comments    : Add code to arrive the Merged Item in Godown automatically.Otherwise stock will not show
--				   correctly in Item in Stock Report[Godown wise]   
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateGodownStockMerging]') AND type in (N'P', N'PC'))
BEGIN
	DROP PROCEDURE spUpdateGodownStockMerging
END
GO  
create PROCEDURE spUpdateGodownStockMerging (@intMergeId as int, @intCompanyId as int,@intLocationId as int) AS      
Begin      
  Declare @intTemp as int,@intId as int,@strPrefix as VarChar(50),@strMaxNo as VarChar(50),@intMgdId as int,
  @intMgdItemId as int,@numMgdCostPrice as numeric(18, 8),@intMgdDetailId as int,@numGsStock as numeric(18, 8)      
  ,@intItemCount as int,@intMergeItemId int --===========<Ref No1>
      
  Set NoCount On      
  -- This select query is necessary for running remotely      
  Select 1 Dummy1, 0 Dummy2      
  set @intTemp = 0      
  set @intItemCount=0   --===========<Ref No1> 
       
  -- check if main item id or detail item id exists in unprocessed quantity      
  SELECT @intTemp = COUNT(*) FROM vwQuantityUnProcessed WHERE ItemId IN (
	SELECT mghItemId FROM aHqMergingHeader WHERE mghId = @intMergeId AND mghCompanyId = @intCompanyId      
    UNION ALL      
    SELECT mgdItemId FROM aHqMergingDetails WHERE mgdId = @intMergeId AND mgdCompanyId = @intCompanyId      
    ) AND LocationId = @intLocationId AND LocationType = 'G'      
  --===========<Ref No1>
  SELECT @intMergeItemId = mghItemId FROM aHqMergingHeader WHERE mghId = @intMergeId AND mghCompanyId = @intCompanyId
  --===========<Ref No1>    

    
  -- item ids exist in unprocessed quantity      
  If (@intTemp > 0)      
    Begin      
	  -- check if the record already exists in header      
	  SELECT @intTemp = COUNT(*) FROM loiMergeHeader WHERE lghRefMergeID = @intMergeId AND 
		lghCompanyId = @intCompanyId AND lghGodownId = @intLocationId      
        
	  -- record does not exist in header -- so just insert it      
	  If (@intTemp <= 0)      
		begin         
		  -- generate next id      
		  SELECT @intId = isnull(max(lghId), 0) + 1 FROM loiMergeHeader WHERE lghGodownId = @intLocationId      
			AND lghCompanyId = @intCompanyId      
          
		  -- get prefix      
		  SELECT @strPrefix = Prefix FROM aPrefix WHERE CompanyId = @intCompanyId AND InterfaceId = 1010      
			AND GodownId = @intLocationId      
         
          --set @StrPrefix = @strPrefix + '%'         
		  -- get max no      
		  SELECT @strMaxNo = isnull(max(convert(int, right(lghNo,len(lghNo) - len(@strPrefix)))), 0)       
		  FROM loiMergeHeader WHERE lghCompanyId = @intCompanyId AND len(lghNo) > len(@strPrefix)       
			AND isnumeric(isnull(right(lghNo, len(lghNo) - len(@strPrefix)), 0)) = 1       
			AND substring(lghNo, 1, len(@strPrefix)) = @strPrefix AND lghGodownId = @intLocationId      
          
		  If (@strMaxNo = '0')      
			Begin      
			  set @strMaxNo = @strPrefix + '1'          
			end      
		  else      
			begin      
			  set @strMaxNo = @strPrefix + convert(varchar, (convert(int, @strMaxNo) + 1))      
			end      
          -- generate next no      
          INSERT INTO loiMergeHeader(lghId, lghCompanyId, lghGodownId, lghNo, lghDate,lghRefMergeId,lghItemId,       
			lghTransFinished,lghCancelled, lghUpdatetime, lghQty, lghNoOfRec,rowguid)      
		  (SELECT @intId, @intCompanyId, @intLocationId,@strMaxNo, GetDate(),mghId, mghItemId, 0, 0, GetDate(), 
		    isnull(gsStock, 0), 0,newid() FROM aHqMergingHeader h LEFT OUTER JOIN VwinquiryGodownStock s      
			ON h.mghItemId = s.gsItemId AND @intLocationId = s.gsGodownId WHERE mghId = @intMergeId      
			AND mghCompanyId = @intCompanyId)      
		End      
	  Else -- get the merging id to insert into details      
		Begin      
		  SELECT @intId = lghId, @intLocationId = lghGodownId FROM loiMergeHeader      
		  WHERE lghRefMergeID = @intMergeId AND lghCompanyId = @intCompanyId AND lghGodownId = @intLocationId      
		End      
	  End      
	Else      
	  Begin           -- if no items in unprocessed quantity      
		-- check if the record already exists in header      
		SELECT @intTemp = COUNT(*) FROM loiMergeHeader WHERE lghRefMergeID = @intMergeId      
		  AND lghCompanyId = @intCompanyId AND lghGodownId = @intLocationId      
        -- record does not exist in header -- so just insert it      
		If (@intTemp <= 0)      
		Begin      
		  -- generate next id      
		  SELECT @intId = isnull(max(lghId), 0) + 1 FROM loiMergeHeader      
		  WHERE lghGodownId = @intLocationId AND lghCompanyId = @intCompanyId      
         
		  -- get prefix      
		  SELECT @strPrefix = Prefix FROM aPrefix WHERE CompanyId = @intCompanyId      
			AND InterfaceId = 1010 AND GodownId = @intLocationId      
          --set @StrPrefix = @strPrefix + '%'         
		  -- get max no      
		  SELECT @strMaxNo = isnull(max(convert(int, right(lghNo,len(lghNo) - len(@strPrefix)))), 0)       
		  FROM loiMergeHeader WHERE lghCompanyId = @intCompanyId AND len(lghNo) > len(@strPrefix)       
			AND isnumeric(isnull(right(lghNo,len(lghNo) - len(@strPrefix)), 0)) = 1       
			AND substring(lghNo, 1, len(@strPrefix)) = @strPrefix AND lghGodownId = @intLocationId      
         
		  If (@strMaxNo = '0')      
			Begin      
			  set @strMaxNo = @strPrefix + '1'          
			End      
		  Else      
			Begin      
			  set @strMaxNo = @strPrefix + convert(varchar,(convert(int, @strMaxNo) + 1))      
			End      
			
		  -- generate next no      
          INSERT INTO loiMergeHeader (lghId, lghCompanyId, lghGodownId, lghNo, lghDate,lghRefMergeId, lghItemId,       
			lghTransFinished,lghCancelled, lghUpdatetime, lghQty, lghNoOfRec,rowguid)      
		  (SELECT @intId, @intCompanyId, @intLocationId,@strMaxNo, GetDate(),mghId, mghItemId, 1, 0, GetDate(), 
		    isnull(gsStock, 0), 0,newid() FROM aHqMergingHeader h LEFT OUTER JOIN VwinquiryGodownStock s      
			ON h.mghItemId = s.gsItemId AND @intLocationId = s.gsGodownId WHERE mghId = @intMergeId      
			AND mghCompanyId = @intCompanyId)        
		End      
	  Else -- if header exists, update trans finished      
		Begin      
		  SELECT @intId = lghId, @intLocationId = lghGodownId FROM loiMergeHeader      
		  WHERE lghRefMergeId = @intMergeId AND lghCompanyId = @intCompanyId AND lghGodownId = @intLocationId      
      
		  UPDATE loiMergeHeader SET lghTransFinished = 1 WHERE lghRefMergeId = @intMergeId      
			AND lghCompanyId = @intCompanyId       
		End      
      -- delete records from details if they exist  -- bcos play it safe, after all, triggers are involved      
	  DELETE FROM loiMergeDetails WHERE lgdId = @intId AND lgdCompanyId = @intCompanyId AND lgdGodownId = @intLocationId      
        
	  -- open the cursor      
	  Declare CurGdnDetails Cursor For SELECT mgdId, mgdItemId, mgdCostPrice,mgdDetailId, isnull(gsStock, 0)      
	  FROM aHqMergingDetails LEFT OUTER JOIN VwinquiryGodownStock ON mgdItemId = gsItemId 
		AND @intLocationId = gsGodownId WHERE mgdId = @intMergeId AND mgdCompanyId = @intCompanyId ORDER BY mgdDetailId      
          
	  Open CurGdnDetails      
        Fetch Next From CurGdnDetails Into @intMgdId, @intMgdItemId, @numMgdCostPrice, @intMgdDetailId,@numGsStock      
        While @@Fetch_Status = 0      
		  Begin      
			INSERT INTO loiMergeDetails (lgdId, lgdCompanyId, lgdGodownId, lgdItemId,lgsdQty, lgdDetailId,rowguid)      
			VALUES (@intId, @intCompanyId, @intLocationId,@intMgdItemId, @numGsStock, @intMgdDetailId,newid())      
			--==========================================<<Ref No1>>
			if @numGsStock > 0
			  begin
				SELECT @intItemCount = COUNT(*) FROM aGodownDetail 
				WHERE  GodownID = @intLocationId and ItemID=@intMergeItemId
				If (@intItemCount <= 0)  		
				  begin
					insert into aGodownDetail values(@intLocationId,@intMergeItemId,0,0,0,0,NEWID())
				  end	
			  end		  
			--==========================================<<Ref No1>>
			Fetch Next From CurGdnDetails InTo @intMgdId, @intMgdItemId, @numMgdCostPrice,@intMgdDetailId,@numGsStock            
		  End      
      close CurGdnDetails      
	  Deallocate CurGdnDetails      
      -- update no. of records      
	  UPDATE loiMergeHeader SET lghNoOfRec = (SELECT COUNT(*) FROM loiMergeDetails WHERE lgdId = @intId AND 
	    lgdCompanyId = @intCompanyId AND lgdGodownId = @intLocationId) WHERE lghId = @intId AND 
	    lghCompanyId = @intCompanyId  AND lghGodownId = @intLocationId      
		-- now update stock      
	  Execute spUpdateGodownItemMerge @intId, @intLocationId, @intCompanyId, 'f'      
	  
	  -- and then update location wise stock      
	  Execute spUpdateGodownLocationItemMerge @intId, @intLocationId, @intCompanyId --, 'f'      
	End      
  Set NoCount Off      
End      
		---------------------------------------------------------     
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_022
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'SpGroupLevelOrdering' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE SpGroupLevelOrdering
end
GO
/*  
--SpGroupLevelOrdering 1,1    
--Created By   : dheena , Hariharan, Hariharan     
--Created Date : 24/05/2004, 27/05/2004, 31/05/2004    
--Purpose      : Groupwise display, corrected depid wise filteration    
-- modified : venkitesh 28/05/2004    
--Purpose      : Added accountid , Given condition for removing unnecessary groups    
-----------------------------------------------------------------------------------  
Ref No   : 01  
Altered By  : Shine Das  
Referer Task No : M_022 from 'Magnolia Issue Tracking System' ExcelSheet  
Purpose   : In this SP there was a conditions written to filter active accounts only.  
But in BalanceSheet it is not required. So it commented.  
-----------------------------------------------------------------------------------  
*/  
CREATE Procedure SpGroupLevelOrdering( @intCompanyID as int,     
                                      @intDepartmentId as int=0) as     
Begin    
 Declare     
  @intGroupID as int,    
    @intMaxGroupID as int,    
  @intRowCount as int,    
  @intCount as int,    
  @IntHcount as int,    
  @intMaxGid as int,    
  @IntScount as int,     
  @intS1Count as int     
    
 set nocount on      
    
 CREATE TABLE #Temp1(T1GID int)     
 CREATE TABLE #Temp2(T2GID int,T2PGId int)    
 CREATE TABLE #Result (GroupID  int,OrderID int,OrderNo  int identity(1,1))    
 CREATE TABLE #SubResult (GroupID  int,OrderID int,OrderNo  int identity(1,1))    
 CREATE TABLE #Stack(GroupID int)    
    
    
 CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),     
   AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,     
   orderno int, levelcode int, departmentid int,     
   DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))     
     
 --header Only insert    
 Insert into #temp1    
 Select     
  Groupid from     
  (Select     
   GroupDesc, Case AccountType     
   When 'A' then 1 when 'L' then 2 when 'I' then 3    
   when 'E' then 4 end TypeOrder, LevelCode, ParentGroupId,    
   GroupId,AccountType     
  from     
   aGroupMaster    
  where parentgroupid is null and levelcode=1)    
 GroupMaster order by TypeOrder, Levelcode, GroupId    
    
 Insert into #temp2    
 SELECT groupid,Parentgroupid FROM aGroupMaster     
      
 Select @intcount=Count(*) from #temp1       
     
 --Check Headergroupid wise    
 Select @IntHcount=count(*) from #temp1    
    
 While @IntHcount >0     
 Begin     
  Select Top 1 @intGroupid=T1Gid from #temp1      
    
  Insert into #Result(GroupID,OrderID) values(@intGroupid,@intGroupid)    
    
  select @IntScount=count(*) from #temp2      
  Where T2PGid=@intGroupid    
      
  While @IntScount>0    
   Begin    
   select @intMaxGid=Max(T2Gid) from #temp2      
   Where T2PGid=@intGroupid       
    
   Select @intS1Count=count(*) from #temp2      
   Where T2PGid=@intMaxGid    
       
    
   If @intS1Count =0      
   Begin    
    Insert into #SubResult(GroupID,OrderID)values(@intMaxGid,@intGroupid)        
    Delete from #temp2 where T2GId=@intMaxGid             
   End      
   Else    
   Begin    
    While @intS1Count>0    
    Begin    
    
     select @intMaxGid=Max(T2Gid) from #temp2      
     Where T2PGid=@intMaxGid    
    
     if (select count(*) from #temp2  Where T2PGid=@intMaxGid)=0    
     Begin    
          
      Insert into #SubResult(GroupID,OrderID)values(@intMaxGid,@intGroupid)          
      Delete from #temp2 where t2gid=@intMaxGid          
     End          
     Select @intS1Count=count(*) from #temp2      
     Where T2PGid=@intMaxGid          
    End     
    
   End        
   --Delete from #temp2 where T2GId=@intGroupid    
    
   select @IntScount=count(*) from #temp2      
   Where T2PGid=@intGroupid    
    
  End     
  insert into #Result(GroupID,OrderID)    
  select GroupID,OrderID from #SubResult order by orderno desc    
  delete from #SubResult     
       
  Delete from #temp1 where T1GID=@intGroupid    
  Select @IntHcount=count(*) from #temp1     
 End     
 if @intDepartmentId=0     
 Begin    
      
  insert #FilteredResult(groupid , AccountCode ,     
   AccountDesc , groupdesc , parentGroupid ,     
   orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)     
  select       
   a.groupid,c.AccountCode,c.AccountDesc,b.groupdesc,b.parentGroupid    
   ,a.orderno,b.levelcode,'' depId,'' DepName, 0, c.AccountId, AccountType    
  from     
   #result a , aGroupmaster b left outer join aaccountmaster c on     
   ----b.groupid=c.groupid and c.active=1  and b.CompanyID=c.CompanyID  --- Ref No : 01      
   b.groupid=c.groupid and b.CompanyID=c.CompanyID   
  where a.groupid=b.groupid      
  and  b.CompanyID=@intcompanyid    
  Group by a.groupid,c.AccountId, c.AccountCode,c.AccountDesc,b.groupdesc,    
  b.parentGroupid,a.orderno,b.levelcode, c.AccountId, AccountType    
  order by a.orderno asc    
 End    
 Else    
 Begin    
  Insert #FilteredResult(groupid , AccountCode ,     
   AccountDesc , groupdesc , parentGroupid ,     
   orderno , levelcode , departmentid , DepartmentName, Checked, c.AccountId, AccType)     
  select       
   a.groupid,c.AccountCode,c.AccountDesc,b.groupdesc,b.parentGroupid    
   ,a.orderno,b.levelcode,d.departmentid depId,d.DepartmentName DepName, 0, c.AccountId, AccountType     
  from     
   #result a , aGroupmaster b left outer join aaccountmaster c on     
   --b.groupid=c.groupid and c.active=1 and b.CompanyID=c.CompanyID    --- Ref No : 01   
     b.groupid=c.groupid and b.CompanyID=c.CompanyID    
   left Outer join (Select * from     
   aDeptAccounts where daCompanyId = @intCompanyId and     
   daDepartmentid = @intDepartmentId) aDeptAccounts on     
   c.AccountID=daAccountID and    
   c.CompanyID=daCompanyID     
   left Outer join adepartmentmaster d on     
   daCompanyId=d.CompanyID and daDepartmentID = d.DepartmentID        
   and daDepartmentID  = @intDepartmentId    
  where a.groupid=b.groupid and  b.CompanyID=@intcompanyid     
  and (daDepartmentID = @intDepartmentid or AccountDesc is null)    
  Group by a.groupid,c.AccountCode,c.AccountDesc,b.groupdesc,    
  b.parentGroupid,a.orderno,b.levelcode ,d.departmentid,d.DepartmentName,     
  c.AccountId, AccountType    
  order by a.orderno asc    
 End    
    
 drop table #result    
 drop table #Stack    
 drop table #temp1    
 drop table #temp2     
 Drop table #SubResult    
     
 set @intGroupId = 0     
 set @IntHcount = 0    
    
 -- TO avoid the groups which does not have any accounts information    
 Select top 1 @intGroupId = GroupId From #FilteredResult where Checked = 0    
 Order by OrderNo Desc    
    
 While @intGroupId <>0     
 Begin    
  set @intCount = 0     
  Select @intCount = count(*) from #FilteredResult where     
  ((AccountDesc is not Null and Groupid= @intGroupId)    
   or ParentGroupid = @intGroupId)    
    
  if @intCount = 0     
   Delete from #FilteredResult where GroupId = @intGroupId    
  else    
   Update #FilteredResult set Checked = 1 where Groupid = @intGroupId    
    
  Set @intGroupId  = 0    
    
  set @IntHcount = @IntHcount + 1    
    
  Select top 1 @intGroupId = GroupId From #FilteredResult where Checked = 0    
  Order by OrderNo Desc    
    
 End     
    
  Select * from #FilteredResult    
    
 Drop Table #FilteredResult    
 set nocount off    
end    


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_071
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
    
    
if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'spBalanceSheet' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE spBalanceSheet
end
GO
-- Last Modified : 28/04/2004, 02/06/2004, 13/07/2004      
-- Modified by   : Hariharan R      
--Comments  : Taken from dep wise sp avoiding loooping for acccount balances      
--   : verified the script       
/*      
exec spBalanceSheet '20100520',1,1      
*/      
-----------------------------------------------------    
--Ref.No:1    
--Modifted By:Aadyakumar.D.V    
--Modified On:03/11/2011    
--Reason      :String or binary data would be truncated,bug came so field length is increased      
-----------------------------------------------------    
--Ref.No:2  
--Modifted By:Shine Das  
--Modified On:09/03/2012    
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"   
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).   
--It has to be corrected.  
-----------------------------------------------------    
CREATE proc spBalanceSheet (@strToDate as varchar(10), @intCompanyID as int,       
@intlevel as int =0) as      
Begin      
    set nocount on      
    Declare @AcCode as varchar(100),      
 @AcID as int,      
 @dblDebit as numeric(18,2),      
 @dblCredit as numeric(18,2),      
 @GroupDesc as varchar(100),      
 @GroupID as int,      
 @dtToDate as datetime,      
 @dtFromDate as datetime,      
 @strFromdate as varchar(10),       
 @intCount as integer,       
 @intFinId as int,       
 @dtPrevFinUnclosedSDate as datetime,       
 @dtLastFinUnclosedEDate as datetime,       
 @intLastFinId as int      
      
Create table #vwJournalDetails(companyid int,      
journalid int,      
journaldetailid int,      
journalcredit bit,      
accountid int,      
Amount numeric(18,2),      
ActualAmount numeric(18,2),      
departmentid int,      
depamount numeric(18,2),       
PostGroup int)      
      
Create table #Tempjournalheader      
(JournalID int,      
CompanyID int,      
JournalDate smalldatetime,       
--ReferenceNo varchar(100),       
--Remarks varchar(250),      
--Type char(10),       
--ReferenceNo varchar(50),--Ref.No:1       
ReferenceNo varchar(100),--Ref.No:1       
Remarks varchar(1000),      
Type varchar(10),       
Cancel bit,       
Realised bit,       
CurrencyId int,       
FinancialID int,       
chequedate datetime,       
updatetime datetime,       
bankdate datetime)      
      
    Create table #BalSheet(      
 CompanyID int,      
 AccCode varchar(100),      
 AcDesc varchar(100),      
 AcType varchar(1),      
 GroupID int,      
 GroupName varchar(100),      
 OBDr numeric(18,2),      
 OBCr numeric(18,2),      
 DebitAmt numeric(18,2),      
 CreditAmt numeric(18,2),      
 ParentGroupID int,AccId int)      
      
   CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),       
  AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,       
  orderno int, levelcode int, departmentid int,       
  DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))       
      
    Create table #BalSheetFinal(      
 CompanyID int,      
 AccCode varchar(100),      
 AcDesc varchar(100),      
 AcType varchar(1),      
 GroupID int,      
 GroupName varchar(100),      
 OBDr numeric(18,2),      
 OBCr numeric(18,2),      
 DebitAmt numeric(18,2),      
 CreditAmt numeric(18,2),      
 AccId int, DepartmentId int, orderno int,       
 levelcode int,       
 Checked int,       
 ProfitLoss Numeric(18,2),      
 ParentGroupId int)      
      
 set @dtToDate = CONVERT(DATETIME,@strToDate)      
      
 select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),       
        @intFinId = financialid from vwfinyearperiod       
        where convert(datetime,@strToDate,101) between sdate and edate      
      
  select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )      
      
 Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening       
 where CompanyId = @intCompanyId and FinancialId <= @intFinId      
      
 --if @intLastFinId = 0   --Ref.No:2 Commented  
  if ISNULL(@intLastFinId,0) = 0      --Ref.No:2 Added  
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod      
  where financialid = (Select min(financialid) from afinancialyear where      
  companyid = @intCompanyId ) and CompanyId= @intCompanyId      
 ELSE      
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod      
  where financialid = @intLastFinId and CompanyId= @intCompanyId      
      
      
 insert #Tempjournalheader       
 Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate      
 and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId      
      
 insert #vwJournalDetails      
 Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where       
 Journaldate>=@dtPrevFinUnclosedSDate and      
 JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId      
 and h.Cancel = 0 and h.CompanyId = @intCompanyId       
      
      
 Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName,       
 OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId)       
 SELECT am.CompanyId, AccountCode, AccountDesc, AccountType, GM.GroupID,       
 GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt, ParentGroupID, AccountID       
 FROM aAccountMaster AM, aGroupMaster GM WHERE GM.GroupID = AM.GroupID AND    (GM.AccountType = 'A' OR GM.AccountType = 'L') AND GM.CompanyID = am.companyid       
 AND AM.CompanyID = @intCompanyID       
       
 Update #BalSheet set OBDr = opening.Openingamount from (Select AccountId,       
 CompanyId, Sum(Openingamount) Openingamount from aaccountfinyearopening where       
 Financialid = @intLastFinId and CompanyId = @intCompanyId Group By CompanyId,       
 AccountId) opening Where opening.Accountid = #BalSheet.AccId and       
 opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId      
      
 Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,       
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v,       
 #TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and       
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and       
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId ) trialDeb       
 Where trialDeb.Accountid = #BalSheet.AccId and       
 trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId      
 and #BalSheet.AcType ='A'      
      
 Update #BalSheet set OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,       
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v,       
 #TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and       
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and       
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId) trialDeb       
 Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID       
 and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType ='A'      
      
 Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,       
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v ,       
 #TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and       
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and       
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId) trialDeb       
 Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID       
 and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType ='L'      
      
 Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,       
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v ,       
 #TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and       
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and       
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId) trialDeb       
 Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID       
 and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType ='L'      
      
 Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,       
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v,       
 #TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and       
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtFROMDate and       
 h.JournalDate <= @dtToDate group by v.CompanyId, v.AccountId) trialDeb Where       
 trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID       
 and trialDeb.CompanyId = @intCompanyId      
      
 Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,       
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From       
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and       
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and       
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate       
 group by v.CompanyId, v.AccountId) trialDeb Where       
 trialDeb.Accountid = #BalSheet.AccId and       
 trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId      
      
 set  @intCount = 0      
      
      
    SET @dblDebit = 0.0      
    SET @dblCredit = 0.0      
        
    if @intFinId > (Select max(financialid) from aAccountfinyearopening where       
    CompanyId = @intCOmpanyId )        
    Begin      
     select @dtPrevFinUnclosedSDate = sdate from vwfinyearperiod where       
     CompanyId = @intCompanyId       
     and FinancialId = (Select max(financialid) from aAccountfinyearopening where       
      CompanyId = @intCOmpanyId )      
      
     select @dblDebit = Sum(isnull(Amount,0))       
     from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g      
     where g.groupid = a.groupid and  d.accountid = a.accountid and       
     h.journalid = d.journalid and h.companyid = d.companyid       
     and h.cancel =0 and journalcredit = 0 and       
     (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )       
      and (accounttype ='e' or accounttype ='i') and h.financialid > 0       
      
     select @dblCredit = Sum(isnull(Amount,0))       
     from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g      
     where g.groupid = a.groupid and  d.accountid = a.accountid and       
     h.journalid = d.journalid and h.companyid = d.companyid       
     and h.cancel =0 and journalcredit = 1 and       
     (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )       
     and (accounttype ='e' or accounttype ='i' ) and h.financialid > 0       
      
     if isnull(@dblDebit,0) + isnull(@dblCredit,0) >0       
  Begin      
   Update #BalSheet set OBDr = isnull(OBDr,0) +       
   (isnull(@dblCredit,0)) - isnull(@dblDebit,0) , OBCr = 0      
   where AccId = (Select RetainedEarningsAcc from aSettings where       
   CompanyId = @intCompanyId)      
  End        
        
    End       
      
    set @dblDebit = 0.0      
    set @dblCredit = 0.0      
    /*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId       
    and FinancialId = (Select max(financialid) from aAccountfinyearopening where       
    CompanyId = @intCompanyId ) */      
      
    select @dblDebit = Sum(isnull(Amount,0))       
    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g      
    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid       
    and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and       
    (accounttype ='e' or accounttype ='i') and h.financialid > 0       
      
    select @dblCredit = Sum(isnull(Amount,0))       
    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g      
    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid       
    and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and       
    (accounttype ='e' or accounttype ='i' ) and h.financialid > 0       
      
 Insert #FilteredResult(groupid , AccountCode ,       
  AccountDesc , groupdesc , parentGroupid ,       
   orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)       
 exec SpGroupLevelOrdering @intCompanyId, 0      
      
Insert #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,       
 OBCr, DebitAmt, CreditAmt, AccId, orderno, levelcode, Checked,       
 ProfitLoss, ParentGroupId)      
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,       
 b.OBCr, b.DebitAmt, b.CreditAmt, b.AccId, r.OrderNo, r.LevelCode,       
 0,  isnull(@dblDebit,0) - isnull(@dblCredit,0) Bal, r.ParentGroupId from #FilteredResult r       
 left outer join #balsheet b on  ((r.GroupId = b.GroupId  and r.AccountId is null)       
 or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and r.AccountId is not null))      
 where ((((isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) - isnull(creditamt,0))       
 <> 0 and isnull(AcType,'') ='A') or ((isnull(obdr,0) + isnull(obcr,0) +       
 isnull(creditamt,0)) -  isnull(debitamt,0) <> 0 and isnull(AcType,'') ='L') and       
 b.accCode is not null) or b.accCode is null) and (r.AccType ='A' or r.AccType ='L' )      
 order by r.orderno      
set @GroupId = 0       
      
-- TO avoid the groups which does not have any accounts information      
 Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0      
 Order by OrderNo Desc      
      
 While @GroupID <>0       
 Begin      
  set @intCount = 0       
  Select @intCount = count(*) from #BalSheetFinal where       
  ((AcDesc is not Null and Groupid= @GroupID)      
   or ParentGroupid = @GroupID)      
      
  if @intCount = 0       
   Delete from #BalSheetFinal where GroupId = @GroupID      
  else      
   Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID      
      
  Set @GroupID  = 0      
      
  Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0      
  Order by OrderNo Desc      
      
 End       
      
 Set @GroupID  = 0      
      
 if @intLevel>0      
 Delete from #BalSheetFinal where LevelCode >= @intLevel and AccId is null      
      
 Select * from #BalSheetFinal order by OrderNo       
      
drop table #BalSheet       
drop table #Tempjournalheader      
drop table #vwJournalDetails      
Drop Table #FilteredResult      
Drop table #BalSheetFinal      
      
set nocount off      
End      

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_071
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'spBalanceSheet_Detail' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE spBalanceSheet_Detail
end
GO                 
--Created By :Benzigar S D              
--Created On :26/07/2010              
--Details    :To get Balance sheet teport with Department waise splitup    
--Modified By :Sreejith G A        
--Created On :28/07/2010              
--Details    :To get Balance sheet teport with Department waise splitup     
--Ref.No:2  
--Modifted By:Shine Das  
--Modified On:09/03/2012    
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"   
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).   
--It has to be corrected.  
----------------------------------------------------- 
         
CREATE proc dbo.spBalanceSheet_Detail (@strToDate as varchar(10), @intCompanyID as int,                     
@intlevel as int =0) as                    
Begin                    
    set nocount on                    
    Declare @AcCode as varchar(100),                    
 @AcID as int,                    
 @dblDebit as numeric(18,2),                    
 @dblCredit as numeric(18,2),                    
 @GroupDesc as varchar(100),                    
 @GroupID as int,                    
 @dtToDate as datetime,                    
 @dtFromDate as datetime,                    
 @strFromdate as varchar(10),                     
 @intCount as integer,                     
 @intFinId as int,                     
 @dtPrevFinUnclosedSDate as datetime,                     
 @dtLastFinUnclosedEDate as datetime,                     
 @intLastFinId as int          
           
                    
Create table #vwJournalDetails(companyid int,                    
journalid int,                    
journaldetailid int,                    
journalcredit bit,                    
accountid int,                    
Amount numeric(18,2),                    
ActualAmount numeric(18,2),                    
departmentid int,                    
depamount numeric(18,2),                     
PostGroup int)                    
                    
Create table #Tempjournalheader                    
                    
(JournalID int,                    
CompanyID int,                    
JournalDate smalldatetime,                     
ReferenceNo varchar(100),                     
Remarks varchar(1000),  --jyothish changed 250 to 1000                  
Type char(10),                     
Cancel bit,                     
Realised bit,                     
CurrencyId int,                     
FinancialID int,                     
chequedate datetime,                     
updatetime datetime,                     
bankdate datetime)                    
                    
                   
                    
    Create table #BalSheet(                    
 CompanyID int,                    
 AccCode varchar(100),                    
 AcDesc varchar(100),                    
 AcType varchar(1),                    
 GroupID int,                    
 GroupName varchar(100),                    
 OBDr numeric(18,2),                    
 OBCr numeric(18,2),                    
 DebitAmt numeric(18,2),                    
 CreditAmt numeric(18,2),                    
 ParentGroupID int,AccId int,departmentid int)           
          
   CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),                     
  AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,                     
  orderno int, levelcode int, departmentid int,                     
  DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))                     
                    
    Create table #BalSheetFinal(                  
 CompanyID int,                    
 AccCode varchar(100),                    
 AcDesc varchar(100),                    
 AcType varchar(1),                    
 GroupID int,                    
 GroupName varchar(100),                    
 OBDr numeric(18,2),                    
 OBCr numeric(18,2),                    
 DebitAmt numeric(18,2),                    
 CreditAmt numeric(18,2),                    
 AccId int, DepartmentId int, orderno int,                     
 levelcode int,                     
 Checked int,                     
 ProfitLoss Numeric(18,2),                    
 ParentGroupId int,DepartmentName varchar(50))                    
                    
 set @dtToDate = CONVERT(DATETIME,@strToDate)                    
                 
 select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),                     
        @intFinId = financialid from vwfinyearperiod                     
        where convert(datetime,@strToDate,101) between sdate and edate                    
                    
  select @dtLastFinUnclosedEDate = dateadd(day, -1, @dtFromDate )                    
                    
 Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening                     
 where CompanyId = @intCompanyId and FinancialId <= @intFinId                    
                    
 --if @intLastFinId = 0    --Ref.No:2  Commented  
  if ISNULL(@intLastFinId,0) = 0    --Ref.No:2 Added               
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod                    
  where financialid = (Select min(financialid) from afinancialyear where                    
  companyid = @intCompanyId ) and CompanyId= @intCompanyId                    
 ELSE                    
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod                    
  where financialid = @intLastFinId and CompanyId= @intCompanyId                    
                    
                    
 insert #Tempjournalheader                     
 Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate                    
 and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId                    
                    
 insert #vwJournalDetails                    
 Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where                     
 Journaldate>=@dtPrevFinUnclosedSDate and                    
 JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId                    
 and h.Cancel = 0 and h.CompanyId = @intCompanyId                     
            
      
          
          
      
      
 Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, ------NEW MODIFIED                   
 OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId, departmentid)       
 select  vss.CompanyId, vss.AccountCode, vss.AccountDesc, vss.AccountType, vss.GroupID,                     
 vss.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,vss.ParentGroupID, vss.AccountID,vss.departmentid        
 from                    
 (SELECT   ad.CompanyId, AM.AccountCode, AM.AccountDesc, GM.AccountType, GM.GroupID,                     
 GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, ad.AccountID,ad.departmentid        
 from aaccountfinyearopening ad      
 left outer join   aaccountmaster AM on AM.accountid=ad.accountid      
 left outer join agroupmaster gm on GM.GroupID = AM.GroupID      
 union all      
 SELECT   v.CompanyId, AM.AccountCode,AM.AccountDesc,GM.AccountType, GM.GroupID,                     
 GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,GM.ParentGroupID, v.AccountID,v.departmentid       
 from  #vwJournalDetails v       
 left outer join   aaccountmaster AM on AM.accountid=v.accountid      
 left outer join agroupmaster gm on GM.GroupID = AM.GroupID      
)vss      
 where      
 (VSS.AccountType = 'A' OR VSS.AccountType = 'L')       
 AND VSS.CompanyID =@intCompanyID   group by  AccountID,departmentid , CompanyId, AccountCode, AccountDesc, AccountType, GroupID,                     
 GroupDesc,ParentGroupID      
      
    
      
            
 Update #BalSheet set  OBDr = opening.Openingamount from (Select AccountId,                     
 CompanyId, Sum(Openingamount) Openingamount,departmentid from aaccountfinyearopening where                     
 Financialid = @intLastFinId and CompanyId = @intCompanyId Group By CompanyId,                     
 AccountId,departmentid) opening Where opening.Accountid = #BalSheet.AccId and                     
 opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId              
 and opening.departmentid= #BalSheet.departmentid                   
                   
          
       
      
 Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,        
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From #vwJournalDetails v,                     
 #TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and                     
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and                     
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb                     
 Where trialDeb.Accountid = #BalSheet.AccId and                     
 trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId                    
 and #BalSheet.AcType ='A' and trialDeb.departmentid=#BalSheet.departmentid                    
                  
      
                
 Update #BalSheet set  OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,                     
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount,v.departmentid From #vwJournalDetails v,                     
 #TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and                     
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and                     
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb                     
 Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID                     
 and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType ='A'              
 and trialDeb.departmentid=#BalSheet.departmentid                    
                    
          
 Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,                     
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,                     
 #TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and                     
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and                     
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb                     
 Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID                     
 and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType ='L'              
 and trialDeb.departmentid=#BalSheet.departmentid                     
                    
          
          
 Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,                     
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From #vwJournalDetails v ,                     
 #TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and                     
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and                     
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.CompanyId, v.AccountId, v.departmentid) trialDeb                     
 Where trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID                     
 and trialDeb.CompanyId = @intCompanyId and #BalSheet.AcType ='L'                
 and trialDeb.departmentid=#BalSheet.departmentid                  
          
          
 Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,                     
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.Departmentid From #vwJournalDetails v,                     
 #TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and                     
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtFROMDate and                     
 h.JournalDate <= @dtToDate group by v.CompanyId, v.AccountId, v.Departmentid) trialDeb Where                     
 trialDeb.Accountid = #BalSheet.AccId and trialDeb.CompanyId = #BalSheet.CompanyID                     
 and trialDeb.CompanyId = @intCompanyId and trialDeb.Departmentid=#BalSheet.departmentid                 
                    
 Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,                     
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount, v.departmentid From                     
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and                     
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and                     
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate                    
 group by v.CompanyId, v.AccountId, v.departmentid) trialDeb Where                     
 trialDeb.Accountid = #BalSheet.AccId and                     
 trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId              
 and trialDeb.departmentid = #BalSheet.departmentid                      
      
      
         
 set  @intCount = 0                    
                    
                    
    SET @dblDebit = 0.0                    
    SET @dblCredit = 0.0                    
                      
    if @intFinId > (Select max(financialid) from aAccountfinyearopening where                     
    CompanyId = @intCOmpanyId )                      
    Begin                    
     select @dtPrevFinUnclosedSDate = sdate from vwfinyearperiod where                     
     CompanyId = @intCompanyId                     
     and FinancialId = (Select max(financialid) from aAccountfinyearopening where                     
      CompanyId = @intCOmpanyId )                    
                    
     select @dblDebit = Sum(isnull(Amount,0))                     
     from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g                    
     where g.groupid = a.groupid and  d.accountid = a.accountid and                     
     h.journalid = d.journalid and h.companyid = d.companyid                     
     and h.cancel =0 and journalcredit = 0 and                     
     (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )                     
      and (accounttype ='e' or accounttype ='i') and h.financialid > 0                     
                    
     select @dblCredit = Sum(isnull(Amount,0))                     
     from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g                    
     where g.groupid = a.groupid and  d.accountid = a.accountid and                     
     h.journalid = d.journalid and h.companyid = d.companyid                     
     and h.cancel =0 and journalcredit = 1 and                     
     (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )                     
     and (accounttype ='e' or accounttype ='i' ) and h.financialid > 0                     
                    
     if isnull(@dblDebit,0) + isnull(@dblCredit,0) >0                     
Begin                    
   Update #BalSheet set OBDr = isnull(OBDr,0) +                     
   (isnull(@dblCredit,0)) - isnull(@dblDebit,0) , OBCr = 0                    
   where AccId = (Select RetainedEarningsAcc from aSettings where                     
   CompanyId = @intCompanyId)                    
  End                      
                      
    End                     
                 
          
             
    set @dblDebit = 0.0                    
    set @dblCredit = 0.0                    
    /*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId                     
    and FinancialId = (Select max(financialid) from aAccountfinyearopening where                     
    CompanyId = @intCompanyId ) */                    
                    
    select @dblDebit = Sum(isnull(Amount,0))                     
    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g                    
    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid                     
    and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and                     
    (accounttype ='e' or accounttype ='i') and h.financialid > 0                     
                    
    select @dblCredit = Sum(isnull(Amount,0))                     
    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g                    
    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid                     
    and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and                     
    (accounttype ='e' or accounttype ='i' ) and h.financialid > 0                     
                    
          
      
      
   Insert #FilteredResult(groupid , AccountCode ,        
    AccountDesc , groupdesc , parentGroupid ,                     
     orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)                     
--   exec SpGroupLevelOrdering_DETAIL @intCompanyId, 0          
   exec SpGroupLevelOrdering @intCompanyId, 0         
      
          
                    
              
Insert #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,                     
 OBCr, DebitAmt, CreditAmt, AccId, Departmentid, DepartmentName, orderno, levelcode, Checked,                     
 ProfitLoss, ParentGroupId)                    
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, b.OBDr,                     
 b.OBCr, b.DebitAmt, b.CreditAmt, b.AccId,b.Departmentid, ad.DepartmentName, r.OrderNo, r.LevelCode,                     
 0,  isnull(@dblDebit,0) - isnull(@dblCredit,0) Bal, r.ParentGroupId from #FilteredResult r                     
 left outer join #balsheet b on  ((r.GroupId = b.GroupId  and r.AccountId is null  )                     
 or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and r.AccountId is not null ))      
 left outer join adepartmentmaster ad on ad.departmentid=b.departmentid                      
 where ((((isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) - isnull(creditamt,0))                     
 <> 0 and isnull(AcType,'') ='A') or ((isnull(obdr,0) + isnull(obcr,0) +                     
 isnull(creditamt,0)) -  isnull(debitamt,0) <> 0 and isnull(AcType,'') ='L') and                     
 b.accCode is not null) or b.accCode is null) and (r.AccType ='A' or r.AccType ='L' )              
--and r.departmentid=b.departmentid                    
 order by r.orderno                    
set @GroupId = 0         
      
      
                
-- TO avoid the groups which does not have any accounts information                    
 Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0                    
 Order by OrderNo Desc                    
                    
 While @GroupID <>0                     
 Begin                    
  set @intCount = 0                     
  Select @intCount = count(*) from #BalSheetFinal where                     
  ((AcDesc is not Null and Groupid= @GroupID)                    
   or ParentGroupid = @GroupID)                    
                    
  if @intCount = 0                     
   Delete from #BalSheetFinal where GroupId = @GroupID                    
  else                    
   Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID                    
                    
  Set @GroupID  = 0                    
                    
  Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0                    
  Order by OrderNo Desc                    
                    
 End                     
                    
 Set @GroupID  = 0                    
                    
 if @intLevel>0                    
 Delete from #BalSheetFinal where LevelCode >= @intLevel and AccId is null                    
                    
 Select * from #BalSheetFinal order by OrderNo                     
                  
drop table #BalSheet                     
drop table #Tempjournalheader                    
drop table #vwJournalDetails                    
Drop Table #FilteredResult                    
Drop table #BalSheetFinal                    
                    
set nocount off                    
End 

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_071
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'spBalanceSheetDep' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE spBalanceSheetDep
end
GO
-- Last Modified : 01/06/2004, 13/07/2004  
-- Modified by   : Hariharan   
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)  
--               : included consolidation venki 261203  
--   : Removed cursor and given temporary table names  
--   : carry forwarding of unclosed financial year done  
--   : Financialid considerations corrected  
--   : consolidation option department wise is corrected  
--   : Script Verified  

--Ref.No:1
--Modifted By:Shine Das  
--Modified On:09/03/2012    
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"   
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).   
--It has to be corrected.  
----------------------------------------------------- 

/*  
exec spBalanceSheetDep '20100520',1,0,0,0,0  
 */  
CREATE PROCEDURE dbo.spBalanceSheetDep (@strToDate as varchar(10),   
                                        @intCompanyID as int,   
                                        @intDepartmentId as int,   
                                        @bitcons as bit,  
                                        @intlevel as int = 0,  
                                        @intconsolidation as int =0 ) AS  
Begin  
  
    set nocount on  
    Declare @AcCode as varchar(100),  
 @AcID as int,  
 @dblDebit as numeric(18,2),  
 @dblCredit as numeric(18,2),  
 @GroupID as int,  
 @dtToDate as datetime,  
 @dtFromDate as datetime,  
 @strFromdate as varchar(10),   
 @intCount as integer,   
 @intFinId as int,   
 @dtPrevFinUnclosedSDate as datetime,   
 @dtLastFinUnclosedEDate as datetime,   
 @intLastFinId as int  
  
Create table #vwJournalDetails(companyid int,  
journalid int,  
journaldetailid int,  
journalcredit bit,  
accountid int,  
Amount numeric(18,2),  
ActualAmount numeric(18,2),  
departmentid int,  
depamount numeric(18,2),   
PostGroup int)  
  
Create table #Tempjournalheader  
  
(JournalID int,  
CompanyID int,  
JournalDate smalldatetime,   
ReferenceNo varchar(50),   
Remarks varchar(1000),  
Type varchar(10),   
Cancel bit,   
Realised bit,   
CurrencyId int,   
FinancialID int,   
chequedate datetime,   
updatetime datetime,   
bankdate datetime)  
  
    Create table #BalSheet(  
 CompanyID int,  
 AccCode varchar(100),  
 AcDesc varchar(100),  
 AcType varchar(1),  
 GroupID int,  
 GroupName varchar(100),  
 OBDr numeric(18,2),  
 OBCr numeric(18,2),  
 DebitAmt numeric(18,2),  
 CreditAmt numeric(18,2),  
 ParentGroupID int,   
 AccId int,   
 DepartmentId int)  
  
CREATE TABLE #FilteredResult(groupid int , AccountCode Varchar(50),   
   AccountDesc varchar(100), groupdesc Varchar(100), parentGroupid int,   
   orderno int, levelcode int, departmentid int,   
   DepartmentName varchar(50), Checked int, AccountId int, AccType varchar(50))   
  
  
    Create table #BalSheetFinal(  
 CompanyID int,  
 AccCode varchar(100),  
 AcDesc varchar(100),  
 AcType varchar(1),  
 GroupID int,  
 GroupName varchar(100),  
 OBDr numeric(18,2),  
 OBCr numeric(18,2),  
 DebitAmt numeric(18,2),  
 CreditAmt numeric(18,2),  
 AccId int, DepartmentId int, orderno int,   
 levelcode int,   
 Checked int,   
 ProfitLoss Numeric(18,2),  
 ParentGroupId int)  
  
    -- create the temporary table to insert sub departments  
    -- table name is given as #SubDepts1 to avoid conflicts  
-- with #SubDepts inside the sp  
    create table #SubDepts1(DeptId int)  
    if @intconsolidation=0   
             insert into #SubDepts1 values(@intDepartmentId)  
    else  
    -- get the sub depts into the temporary table  
        insert into #SubDepts1 Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId  
  
    set @dtToDate = CONVERT(DATETIME,@strToDate)  
  
 select @dtFromDate = sdate, @strfromdate = convert(varchar,sdate,120),   
        @intFinId = financialid from vwfinyearperiod   
        where convert(datetime,@strToDate,101) between sdate and edate  
  
  select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )  
  
 Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening   
 where CompanyId = @intCompanyId and FinancialId <= @intFinId  
  
 --if @intLastFinId = 0  --Ref.No:1 Commented
  if ISNULL(@intLastFinId,0) = 0   --Ref.No:1 Commented
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod  
  where financialid = (Select min(financialid) from afinancialyear where  
  companyid = @intCompanyId ) and CompanyId= @intCompanyId  
 ELSE  
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod  
  where financialid = @intLastFinId and CompanyId= @intCompanyId  
  
 insert into #Tempjournalheader   
 Select H.* from moajournalheader h (nolock) where journaldate>=@dtPrevFinUnclosedSDate  
 and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId  
  
 insert #vwJournalDetails  
 Select d.* from #Tempjournalheader h, vwJournalDetails d (nolock) where   
 Journaldate>=@dtPrevFinUnclosedSDate and  
 JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId  
 and h.Cancel = 0 and h.CompanyId = @intCompanyId and d.departmentid in   
 (Select Deptid from #SubDepts1)   
------------------------------------------------OK  
 --to change the parent group if level id > 0   
 Insert into #BalSheet(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName,   
 OBDr, OBCr, DebitAmt, CreditAmt, ParentGroupID, AccId, DepartmentID)   
 Select CompanyId, AccountCode, AccountDesc, AccountType, GroupID,   
 GroupDesc, OBDR, OBCR, DebitAmt, CreditAmt, ParentGroupID, AccountID,   
 daDepartmentid from (SELECT am.CompanyId, AccountID, AccountCode, AccountDesc,   
 AccountType, GM.GroupID, GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt,   
 ParentGroupID, daDepartmentid FROM aAccountMaster AM,aGroupMaster GM,   
 adeptAccounts d, #SubDepts1 dep WHERE GM.GroupID = AM.GroupID AND   
 (GM.AccountType = 'A' OR GM.AccountType = 'L') AND GM.CompanyID = am.companyid AND   
 AM.CompanyID = @intCompanyID and am.Accountid = d.daAccountId and   
 am.CompanyId = d.daCompanyId AND d.dadepartmentid = dep.deptid  
 Union   
 SELECT am.CompanyId, am.AccountID, AccountCode, AccountDesc, AccountType, GM.GroupID,   
 GM.GroupDesc, 0 OBDR, 0 OBCR, 0 DebitAmt, 0 CreditAmt, ParentGroupID, dd.deptid   
 FROM aAccountMaster AM,aGroupMaster GM,   
 vwGlobalAccounts d, #SubDepts1 dd WHERE GM.GroupID = AM.GroupID AND (GM.AccountType = 'A' OR   
 GM.AccountType = 'L') AND GM.CompanyID = am.companyid AND AM.CompanyID = @intCompanyID   
 and am.Accountid = d.AccountId and am.CompanyId = d.CompanyId) GrpAcId   
 group by CompanyId, AccountCode, AccountDesc, AccountType, GroupID,   
 GroupDesc, OBDR, OBCR, DebitAmt, CreditAmt, ParentGroupID, AccountID,   
 daDepartmentid ORDER BY GrpAcId.AccountID   
  
 Update #BalSheet set OBDr = opening.Openingamount from (Select AccountId,   
 DepartmentId, CompanyId,   
 case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from   
 aaccountfinyearopening where   
 Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where   
 opening.Accountid = #BalSheet.AccId and opening.DepartmentId = #BalSheet.DepartmentId  
 and opening.CompanyId = #BalSheet.CompanyID and opening.CompanyId = @intCompanyId  
  
  
 Update #BalSheet set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h   
 where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId   
 and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId  
 and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId  
 and #BalSheet.AcType ='A'  
  
 Update #BalSheet set OBDr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h   
 where v.JournalCredit = 1 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId   
 and h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId  
 and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId  
 and #BalSheet.AcType ='A'  
  
 Update #BalSheet set OBCr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,   
 #TempJournalHeader h where v.JournalCredit = 1 and h.JournalId = v.JournalId and   
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and   
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,   
 v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and   
 trialDeb.DepartmentId = #BalSheet.DepartmentId and   
 trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId   
 and #BalSheet.AcType ='L'  
  
 Update #BalSheet set OBCr = OBDr - isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v ,   
 #TempJournalHeader h where v.JournalCredit = 0 and h.JournalId = v.JournalId and   
 h.CompanyId = v.CompanyId and h.JournalDate >= @dtPrevFinUnclosedSDate and   
 h.JournalDate <= @dtLastFinUnclosedEDate group by v.AccountId, v.DepartmentId,   
 v.CompanyId) trialDeb Where trialDeb.Accountid = #BalSheet.AccId and   
 trialDeb.DepartmentId = #BalSheet.DepartmentId and   
 trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId   
 and #BalSheet.AcType ='L'  
  
 Update #BalSheet set DebitAmt = trialDeb.amount from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId, case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From #vwJournalDetails v, #TempJournalHeader h   
 where v.JournalCredit = 0 and h.JournalId = v.JournalId and h.CompanyId = v.CompanyId   
 and h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #BalSheet.AccId and trialDeb.DepartmentId = #BalSheet.DepartmentId   
 and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
 Update #BalSheet set CreditAmt = trialDeb.amount from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId,   
 case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #BalSheet.AccId and   
 trialDeb.DepartmentId = #BalSheet.DepartmentId  
 and trialDeb.CompanyId = #BalSheet.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
 set  @intCount = 0  
  
  
    SET @dblDebit = 0.0  
    SET @dblCredit = 0.0  
    
    if @intFinId > (Select max(financialid) from aAccountfinyearopening where   
    CompanyId = @intCOmpanyId )    
    Begin  
     select @dtPrevFinUnclosedSDate = sdate from vwfinyearperiod where CompanyId = @intCompanyId   
     and FinancialId = (Select max(financialid) from aAccountfinyearopening where   
      CompanyId = @intCOmpanyId )  
  
     select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end  
     from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g  
     where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid   
     and h.cancel =0 and journalcredit = 0 and   
     (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )   
      and (accounttype ='e' or accounttype ='i') and h.financialid > 0   
     and d.departmentid IN (Select DeptId from #SubDepts1)  
  
     select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end  
     from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g  
     where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid   
     and h.cancel =0 and journalcredit = 1 and   
     (journaldate >= @dtPrevFinUnclosedSDate and journaldate <= @dtLastFinUnclosedEDate )   
     and (accounttype ='e' or accounttype ='i' ) and h.financialid > 0   
     and d.departmentid IN (Select DeptId from #SubDepts1)  
  
     if isnull(@dblDebit,0) + isnull(@dblCredit,0) >0   
  Begin  
   Update #BalSheet set OBDr = isnull(OBDr,0) +   
   (isnull(@dblCredit,0)) - isnull(@dblDebit,0) , OBCr = 0  
   where AccId = (Select RetainedEarningsAcc from aSettings where   
   CompanyId = @intCompanyId)  
  End    
    
    End   
  
    set @dblDebit = 0.0  
    set @dblCredit = 0.0  
    /*select @strfromdate = convert(varchar,sdate,120) from vwfinyearperiod where CompanyId = @intCompanyId   
    and FinancialId = (Select max(financialid) from aAccountfinyearopening where   
    CompanyId = @intCompanyId ) */  
  
    select @dblDebit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end  
    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g  
    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid   
    and h.cancel =0 and journalcredit = 0 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and   
    (accounttype ='e' or accounttype ='i') and h.financialid > 0   
    and d.departmentid IN (Select DeptId from #SubDepts1)  
  
    select @dblCredit = case when @bitcons = 1 then Sum(isnull(Amount,0)) else Sum(isnull(depAmount,0)) end  
    from #Tempjournalheader h, #vwJournalDetails d, aaccountmaster a, agroupmaster g  
    where g.groupid = a.groupid and  d.accountid = a.accountid and h.journalid = d.journalid and h.companyid = d.companyid   
    and h.cancel =0 and journalcredit = 1 and (journaldate >= @strfromdate and journaldate <= @strtodate ) and   
    (accounttype ='e' or accounttype ='i' ) and h.financialid > 0   
    and d.departmentid IN (Select DeptId from #SubDepts1)  
  
 --SELECT b.*, isnull(@dblDebit,0) - isnull(@dblCredit,0) as Bal FROM #balsheet b   
 --where (isnull(obdr,0) + isnull(obcr,0) + isnull(debitamt,0) + isnull(creditamt,0)) <> 0  
 --order by b.parentgroupid  
 if @intConsolidation = 0   
 Begin   
  Insert #FilteredResult(groupid , AccountCode ,   
  AccountDesc , groupdesc , parentGroupid ,   
  orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)   
  exec SpGroupLevelOrdering @intCompanyId, @intDepartmentId  
 End  
 Else  
 Begin   
  Insert #FilteredResult(groupid , AccountCode ,   
  AccountDesc , groupdesc , parentGroupid ,   
  orderno , levelcode , departmentid , DepartmentName, Checked, AccountId, AccType)   
  exec SpGroupLevelOrdering @intCompanyId, 0  
 End   
Insert #BalSheetFinal(CompanyID, AccCode, AcDesc, AcType, GroupID, GroupName, OBDr,   
 OBCr, DebitAmt, CreditAmt, AccId, departmentid, orderno, levelcode, Checked,   
 ProfitLoss, ParentGroupId)  
SELECT b.CompanyId, b.AccCode, b.AcDesc, r.AccType, r.GroupId, r.GroupDesc, sum(b.OBDr),   
 sum(b.OBCr), sum(b.DebitAmt), sum(b.CreditAmt), b.AccId, 0, r.OrderNo,   
 r.LevelCode,  0,  isnull(@dblDebit,0) - isnull(@dblCredit,0) Bal, r.ParentGroupId from   
 #FilteredResult r left outer join #balsheet b on  ((r.GroupId = b.GroupId  and   
 r.AccountId is null) or (r.GroupId = b.GroupId  and r.AccountId  = b.AccId and   
 r.AccountId is not null))  
group by b.CompanyId, r.OrderNo, r.AccType, r.GroupId, r.GroupDesc,   
 r.LevelCode, r.ParentGroupId, b.AccId, b.AccCode, b.AcDesc  
having ((((sum(isnull(obdr,0)) + sum(isnull(obcr,0)) + sum(isnull(debitamt,0)) - sum(isnull(creditamt,0))) <> 0 and  
isnull(r.AccType,'') ='A') or ((sum(isnull(obdr,0)) + sum(isnull(obcr,0)) + sum(isnull(creditamt,0))) -  sum(isnull(debitamt,0))   
<> 0 and isnull(r.AccType,'') ='L') and b.accCode is not null) or b.accCode is null)  
and (r.AccType ='A' or r.AccType ='L' )  
order by r.orderno  
  
 set @GroupId = 0   
  
-- TO avoid the groups which does not have any accounts information  
 Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0  
 Order by OrderNo Desc  
  
 While @GroupID <>0   
 Begin  
  set @intCount = 0   
  Select @intCount = count(*) from #BalSheetFinal where   
  ((AcDesc is not Null and Groupid= @GroupID)  
   or ParentGroupid = @GroupID)  
  
  if @intCount = 0   
   Delete from #BalSheetFinal where GroupId = @GroupID  
  else  
   Update #BalSheetFinal set Checked = 1 where Groupid = @GroupID  
  
  Set @GroupID  = 0  
  
  Select top 1 @GroupID = GroupId From #BalSheetFinal where Checked = 0  
  Order by OrderNo Desc  
  
 End   
  
 if @intLevel>0  
 Delete from #BalSheetFinal where LevelCode >= @intLevel and AccId is null  
   
Select * from #BalSheetFinal order by OrderNo   
  
  
Drop Table #Tempjournalheader  
Drop Table #vwJournalDetails  
Drop Table #BalSheet   
Drop Table #FilteredResult  
Drop table #BalSheetFinal  
  
set nocount off  
End  

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_071
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'spTrialBalance' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE spTrialBalance
end
GO
    -- Last Modified : 26/04/2004, 28/07/2004  
-- Modified by   : Hariharan   
--   : Removed Cursor and looping to make the printing fast  
--   : Opening debit and credit taken net and updated  
----------------------------------------------------- 
--Ref.No:1
--Modifted By:Shine Das  
--Modified On:09/03/2012    
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"   
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).   
--It has to be corrected.  
----------------------------------------------------- 

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
 
CREATE PROC dbo.spTrialBalance (@strFromDate as varchar(10),   
                                    @strToDate as varchar(10),   
                                    @intCompanyId as int) AS  
begin  
    set nocount on  
    set ansi_warnings off  
  
    Declare @dtFROMDate as datetime,  
 @dtToDate as datetime,  
 @intParentGroupID int,   
 @intFinId as int,   
 @dtPrevFinUnclosedSDate as datetime,   
 @dtLastFinUnclosedEDate as datetime,   
 @intCount as int,   
 @intLastFinId as int  
  
Create table #vwJournalDetails(companyid int,  
journalid int,  
journaldetailid int,  
journalcredit bit,  
accountid int,  
Amount numeric(18,2),  
ActualAmount numeric(18,2),  
departmentid int,  
depamount numeric(18,2),   
PostGroup int)  
  
Create table #Tempjournalheader  
  
(JournalID int,  
CompanyID int,  
JournalDate smalldatetime,   
ReferenceNo varchar(100),   
Remarks varchar(250),  
Type char(10),   
Cancel bit,   
Realised bit,   
CurrencyId int,   
FinancialID int,   
chequedate datetime,   
updatetime datetime,   
bankdate datetime)  
  
    Create table #TrialBal(  
 CompanyID int,  
 AccCode varchar(100),  
 AccDesc varchar(100),  
 AcType varchar(1),  
 GroupID int,  
 GroupName varchar(100),  
 OBDr numeric(18,2),  
 OBCr numeric(18,2),  
 DebitAmt numeric(18,2),  
 CrEDitAmt numeric(18,2),   
 AccountId int)  
  
   
    SELECT @dtFROMDate = convert(datetime, @strFROMDate)  
    SELECT @dtToDate = convert(datetime, @strToDate)  
  
 Select @intFinId = financialid from vwfinyearperiod   
        where convert(datetime,@strFROMDate,101) between sdate and edate  
  
 select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )  
  
 select @intCount = count(*) from aAccountfinyearOpening where   
 CompanyId = @intCompanyId and FinancialId = @intFinId  
  
 Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening   
 where CompanyId = @intCompanyId and FinancialId <= @intFinId  
  
 --if @intLastFinId = 0   --Ref.No:1 Commented
 
 if ISNULL(@intLastFinId,0) = 0   --Ref.No:1 Added
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod  
  where financialid = (Select min(financialid) from afinancialyear where  
  companyid = @intCompanyId ) and CompanyId= @intCompanyId  
 ELSE  
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod  
  where financialid = @intLastFinId and CompanyId= @intCompanyId  
  
insert #Tempjournalheader   
Select H.* from moajournalheader h where JournalDate>=@dtPrevFinUnclosedSDate and   
 JournalDate <=@dtToDate and h.CompanyId = @intCompanyId  
  
insert #vwJournalDetails  
Select d.* from #Tempjournalheader h, vwJournalDetails d where JournalDate>=@dtPrevFinUnclosedSDate and   
 JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId  
 and h.Cancel = 0 and h.CompanyId = @intCompanyId   
  
     -----------------------------  
    insert into #TrialBal  
    SELECT am.CompanyId, am.AccountCode, am.AccountDesc, gm.accounttype,   
    GM.GroupID, GM.GroupDesc, 0 OpDr, 0 OpCr, 0 Debit, 0 Credit,    
    am.AccountId FROM aaccountmaster AM, aGroupMaster GM  
    WHERE GM.GroupID = AM.GroupID AND GM.CompanyID = AM.CompanyID   
    AND AM.CompanyID = @intcompanyid order by aM.accountid asc  
  
  
 Update #TrialBal set OBDr = abs(opening.Openingamount) from (Select AccountId,   
 CompanyId, sum(Openingamount) Openingamount from aaccountfinyearopening where   
 Financialid = @intLastFinId and CompanyId = @intCompanyId   
 Group BY AccountId, CompanyId) opening Where   
 opening.Accountid = #TrialBal.AccountId and   
 opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId  
 and (((#TrialBal.ACType = 'A' or #TrialBal.ACType = 'E' ) and   
 opening.Openingamount >0) or ((#TrialBal.ACType = 'L' or #TrialBal.ACType = 'I' ) and   
 opening.Openingamount <0))  
  
 Update #TrialBal set OBCr = abs(opening.Openingamount) from (Select AccountId,   
 CompanyId, sum(Openingamount) Openingamount from aaccountfinyearopening where   
 Financialid = @intLastFinId and CompanyId = @intCompanyId   
 Group BY AccountId, CompanyId) opening Where   
 opening.Accountid = #TrialBal.AccountId and   
 opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId  
 and (((#TrialBal.ACType = 'A' or #TrialBal.ACType = 'E' ) and   
 opening.Openingamount <0) or ((#TrialBal.ACType = 'L' or #TrialBal.ACType = 'I' ) and   
 opening.Openingamount >0))  
  
 Update #TrialBal set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate   
 group by v.AccountId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId   
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
 Update #TrialBal set OBCr = OBCr + isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From #vwJournalDetails v ,   
 #TempJournalHeader h where v.JournalCredit = 1 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate   
 group by v.AccountId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and trialDeb.CompanyId = #TrialBal.CompanyID   
 and trialDeb.CompanyId = @intCompanyId  
  
 Update #TrialBal set OBCr = OBCr - OBDr, OBDr =0 where OBCr > OBDr  
  
 Update #TrialBal set OBDr = OBDr - OBCr, OBCr =0 where OBDr > OBCr  
  
 Update #TrialBal set DebitAmt = trialDeb.amount from (Select v.AccountId,   
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate   
 group by v.AccountId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and   
 trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
 Update #TrialBal set CreditAmt = trialDeb.amount from (Select v.AccountId,   
 v.CompanyId, Sum(isnull(v.Amount,0)) Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate   
 group by v.AccountId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and   
 trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
    SELECT * FROM #TrialBal    
    where (isnull(obcr, 0)+  isnull(obdr, 0) + isnull(debitamt, 0) + isnull(creditamt, 0)) <> 0  
    ORDER BY AcType, AccCode  
  
   
    drop table #vwJournalDetails  
    drop table #Tempjournalheader  
    Drop Table #TrialBal    
    set nocount on  
    set ansi_warnings on  
end  

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_071
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'spTrialBalanceConsol' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE spTrialBalanceConsol
end
GO

    --modified by  : Hariharan     
--Modified Date  : 03/02/2004, 20/03/2004, 29/03/2004    
--Comments   : v3 (given depamount instead of amount on bitcon=0 else part)    
--   : used temporary tables for getting data after fetching for first time    
--exec spTrialBalanceConsol '20090107','20100526',1,0,1,1  
-----------------------------  
--Modified by : VinothMurugan V  
--Date : 25/06/2010  
--Refno : RefNo-01  
--Purpose : Extend Verchar Value  
----------------------------  
--Ref.No:2  
--Modifted By:Shine Das  
--Modified On:09/03/2012    
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"   
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).   
--It has to be corrected.  
----------------------------------------------------- 
CREATE proc dbo.spTrialBalanceConsol @strFROMDate as varchar(10), @strToDate as varchar(10),     
@intcompanyid as int, @intdepartmentid as int, @bitcons as bit,    
@intconsolidation as int=0  as    
set nocount on    
begin    
    
declare @dtFROMDate as datetime    
declare @dtToDate as datetime,    
 @intFinId as int,     
 @dtPrevFinUnclosedSDate as datetime,     
 @dtLastFinUnclosedEDate as datetime,     
 @intCount as int,     
 @intLastFinId as int    
    
Create table #vwJournalDetails(companyid int,    
journalid int,    
journaldetailid int,    
journalcredit bit,    
accountid int,    
Amount numeric(18,2),    
ActualAmount numeric(18,2),    
departmentid int,    
depamount numeric(18,2),     
Postgroup int)    
    
Create table #Tempjournalheader    
    
(JournalID int,    
CompanyID int,    
JournalDate smalldatetime,     
ReferenceNo varchar(200),  --RefNo-01   
Remarks varchar(400), --RefNo-01   
Type char(20),  --RefNo-01   
Cancel bit,     
Realised bit,     
CurrencyId int,     
FinancialID int,     
chequedate datetime,     
updatetime datetime,     
bankdate datetime)    
    
    
Create table #TrialBal(    
 CompanyID int,    
 DepartmentId int,    
 DepartmentName varchar(100),     
 accountid int,    
 AccCode varchar(50),     
 AccDesc varchar(100),    
 AcType varchar(1),    
 GroupID int,    
 GroupName varchar(100),    
 Debit numeric(18,2),    
 Credit numeric(18,2),     
 OpDebit numeric(18,2),     
 OpCredit Numeric(18,2),    
 OpBal numeric(18,2))    
    
    
 SELECT @dtFROMDate = convert(datetime, @strFROMDate)    
 SELECT @dtToDate = convert(datetime,@strToDate)    
     
     
 Select @intFinId = financialid from vwfinyearperiod     
        where convert(datetime,@strFROMDate,101) between sdate and edate    
    
 select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )    
    
 select @intCount = count(*) from aAccountfinyearOpening where     
 CompanyId = @intCompanyId and FinancialId = @intFinId    
    
 Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening     
 where CompanyId = @intCompanyId and FinancialId <= @intFinId    
     
     
 --if @intLastFinId = 0   --Ref.No:2  Commented  
 if ISNULL(@intLastFinId,0) = 0   --Ref.No:2  Added
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod    
  where financialid = (Select min(financialid) from afinancialyear where    
  companyid = @intCompanyId ) and CompanyId= @intCompanyId    
 ELSE    
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod    
  where financialid = @intLastFinId and CompanyId= @intCompanyId    
     
 -- create the temporary table to insert sub departments    
    -- table name is given as #SubDepts1 to avoid conflicts    
    -- with #SubDepts inside the sp    
    create table #SubDepts1(DeptId int)     
    if @intconsolidation=0     
             insert into #SubDepts1 values(@intDepartmentId)    
    else    
    -- get the sub depts into the temporary table    
         insert into #SubDepts1    
        Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId    
    
 insert #Tempjournalheader     
 Select H.* from moajournalheader h (NOLOCK) where JournalDate>= @dtPrevFinUnclosedSDate     
 and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId    
 if @intDepartmentId = 0    
 begin    
 insert #vwJournalDetails    
 Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where     
 JournalDate>= @dtPrevFinUnclosedSDate and JournalDate <=@dtToDate and     
 h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and     
 h.CompanyId = @intCompanyId      
 end    
 else    
 begin    
 insert #vwJournalDetails    
 Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where     
 JournalDate>= @dtPrevFinUnclosedSDate and JournalDate <=@dtToDate and     
 h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and     
 h.CompanyId = @intCompanyId and d.departmentid in (Select Deptid from #SubDepts1)     
 end    
    
 insert into #TrialBal(CompanyID, DepartmentId, DepartmentName, accountid, AccCode,     
 AccDesc, AcType, GroupID, GroupName , Debit, Credit, OpBal, OpDebit, OpCredit )     
 Select a.CompanyId, m.DepartmentId, DepartmentName, a.AccountId, a.AccountCode,     
 a.AccountDesc,  g.AccountType, g.GroupID, g.GroupDesc, 0 Debit, 0 Credit, 0 OpBal,     
 0, 0 From aAccountMaster a, aGroupMaster g, aDepartmentMaster m where     
 a.GroupId = g.GroupID and a.CompanyId = g.CompanyId and a.companyid = m.companyid     
 and a.CompanyId = @intCompanyid    
    
 Update #TrialBal set OpBal = opening.Openingamount from (Select AccountId,     
 DepartmentId, CompanyId, Openingamount from aaccountfinyearopening where     
 Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where     
 opening.Accountid = #TrialBal.AccountId and     
 opening.DepartmentId = #TrialBal.DepartmentId    
 and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId    
    
 Update #TrialBal set OpDebit = trialDeb.amount from (Select v.AccountId,     
 v.DepartmentId, v.CompanyId, Sum(isnull(v.Amount,0)) Amount From     
 #vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and     
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and     
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate     
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where     
 trialDeb.Accountid = #TrialBal.AccountId and     
 trialDeb.DepartmentId = #TrialBal.DepartmentId    
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId    
    
 Update #TrialBal set OpCredit = trialDeb.amount from (Select v.AccountId,     
 v.DepartmentId, v.CompanyId, Sum(isnull(v.Amount,0)) Amount From     
 #vwJournalDetails v , MoaJournalHeader h where v.JournalCredit = 1 and     
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and     
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate     
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where     
 trialDeb.Accountid = #TrialBal.AccountId and     
 trialDeb.DepartmentId = #TrialBal.DepartmentId    
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId    
    
 Update #TrialBal set Debit = trialDeb.amount from (Select v.AccountId,     
 v.DepartmentId, v.CompanyId, Sum(isnull(v.Amount,0)) Amount From     
 #vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and     
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and     
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate     
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where     
 trialDeb.Accountid = #TrialBal.AccountId and     
 trialDeb.DepartmentId = #TrialBal.DepartmentId    
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId    
    
 Update #TrialBal set Credit = trialDeb.amount from (Select v.AccountId,     
 v.DepartmentId, v.CompanyId, Sum(isnull(Amount,0)) Amount From     
 #vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 1 and     
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and     
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate     
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where     
 trialDeb.Accountid = #TrialBal.AccountId and     
 trialDeb.DepartmentId = #TrialBal.DepartmentId    
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId    
     
 /*delete from #TrialBal where departmentid in     
 (Select departmentid from #TrialBal group by DepartmentId    
 having sum(debit) = 0 and sum(credit)=0) */    
    
 Delete from #TrialBal from (Select accountid, Departmentid from #TrialBal     
 group by accountid, departmentid having sum(debit) = 0 and sum(credit) = 0 and     
 sum(OpDebit) = 0 and sum(OpCredit)=0 and     
 sum(OpBal)=0 ) chk where #TrialBal.accountid = chk.accountid and    
 #TrialBal.departmentid = chk.departmentid    
     
    
 --TEMPORARY CODE GIVEN TO CONSOLIDATION IMM1, 2 AND 3 AS IMM STORE    
    
 Update #TrialBal set departmentid = 3 where departmentid in (15, 16, 17)    
    
 Select CompanyID, DepartmentId, DepartmentName , accountid,    
 AccCode, AccDesc , AcType , GroupID , GroupName , Debit ,    
 Credit, OpDebit, OpCredit, OpBal , 'Debit' DebitTitle, 'Credit' CreditTitle,     
 case AcType when 'A' then '1' when 'L' THEN '2' WHEN 'I' then '3'    
 WHEN 'E' THEN '4' end GroupNo from #TrialBal     
 order by AcType, GroupId, AccountId    
    
    --drop table #TrialBal    
    drop table #SubDepts1    
    drop table #vwJournalDetails    
    drop table #Tempjournalheader     
end    
set nocount off    
    
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_071
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'spTrialBalanceDep' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE spTrialBalanceDep
end
GO
    -- Last Modified : 26/04/2004, 13/07/2004, 28/07/2004  
-- Modified by   : Kishore, Hariharan   
-- Comments  : the department accoiunt filter given (23/01/2003)  
--               : removed account head filteration deptwise (25/08/2003)  
--               : Included subdepartmetns of given dept in the filteration (11/12/2003)  
--   : Included consolidation 261203 venki  
--   : Hari corrected the A, L, I ,E TYPE checking and made temporary table source  
--   : Removed Cursor and looping to make the printing fast  
--   : COnsolidation group corrected avoiding departmentid from grouping  
--   : Opening Debit and credit net is found and kept in opening columns  
----------------------------------------
--Ref.No:1 
--Modifted By:Shine Das  
--Modified On:09/03/2012    
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"   
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).   
--It has to be corrected.  
-----------------------------------------------------    
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
CREATE PROC dbo.spTrialBalanceDep (@strFromDate as varchar(10),   
                                    @strToDate as varchar(10),   
                                    @intCompanyId as int,   
                                    @intDepartmentId as int,   
                                    @bitCons as bit,  
                                    @intLevel as int = 0,  
        @intconsolidation as int =0) AS  
begin  
    set nocount on  
    set ansi_warnings off  
  
    Declare   
 @dtFROMDate as datetime,  
 @dtToDate as datetime,  
 @intParentGroupID int,   
 @intFinId as int,   
 @dtPrevFinUnclosedSDate as datetime,   
 @dtLastFinUnclosedEDate as datetime,   
 @intCount as int,   
 @intLastFinId as int  
  
Create table #vwJournalDetails(companyid int,  
journalid int,  
journaldetailid int,  
journalcredit bit,  
accountid int,  
Amount numeric(18,2),  
ActualAmount numeric(18,2),  
departmentid int,  
depamount numeric(18,2),   
PostGroup int)  
  
Create table #Tempjournalheader  
  
(JournalID int,  
CompanyID int,  
JournalDate smalldatetime,   
ReferenceNo varchar(100),   
Remarks varchar(250),  
Type char(10),   
Cancel bit,   
Realised bit,   
CurrencyId int,   
FinancialID int,   
chequedate datetime,   
updatetime datetime,   
bankdate datetime)  
  
    Create table #TrialBal(  
 CompanyID int,  
 AccCode varchar(100),  
 AccDesc varchar(100),  
 AcType varchar(1),  
 GroupID int,  
 GroupName varchar(100),  
 OBDr numeric(18,2),  
 OBCr numeric(18,2),  
 DebitAmt numeric(18,2),  
 CrEDitAmt numeric(18,2),   
 OpDebit numeric(18,2),   
 OpCredit Numeric(18,2),   
 AccountId int,   
 DepartmentId int)  
  
    -- create the temporary table to insert sub departments  
    -- table name is given as #SubDepts1 to avoid conflicts  
    -- with #SubDepts inside the sp  
    create table #SubDepts1(DeptId int)  
   if @intconsolidation=0   
     insert into #SubDepts1 values(@intDepartmentId)  
   else  
    -- get the sub depts  
    insert into #SubDepts1  
        Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId  
   
    SELECT @dtFROMDate = convert(datetime, @strFROMDate)  
    SELECT @dtToDate = convert(datetime, @strToDate)  
  
 Select @intFinId = financialid from vwfinyearperiod   
        where convert(datetime,@strFROMDate,101) between sdate and edate  
  
 select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )  
  
 select @intCount = count(*) from aAccountfinyearOpening where   
 CompanyId = @intCompanyId and FinancialId = @intFinId  
  
 Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening   
 where CompanyId = @intCompanyId and FinancialId <= @intFinId  
  
 --if @intLastFinId = 0   --Ref.No:1 Commented
 if ISNULL(@intLastFinId,0) = 0   --Ref.No:1 Added
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod  
  where financialid = (Select min(financialid) from afinancialyear where  
  companyid = @intCompanyId ) and CompanyId= @intCompanyId  
 ELSE  
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod  
  where financialid = @intLastFinId and CompanyId= @intCompanyId  
  
insert #Tempjournalheader   
Select H.* from moajournalheader h where JournalDate>=@dtPrevFinUnclosedSDate and   
 JournalDate <=@dtToDate and h.CompanyId = @intCompanyId  
  
insert #vwJournalDetails  
Select d.* from #Tempjournalheader h, vwJournalDetails d where JournalDate>=@dtPrevFinUnclosedSDate and   
 JournalDate <=@dtToDate and h.JournalId = d.JournalId and h.CompanyId = d.CompanyId  
 and h.Cancel = 0 and h.CompanyId = @intCompanyId and d.departmentid in   
 (Select Deptid from #SubDepts1)   
  
     -----------------------------  
    insert into #TrialBal  
     SELECT acc.CompanyId, acc.AccountCode, acc.AccountDesc, acc.accounttype,   
    acc.GroupID, acc.GroupDesc, OpDr, OpCr, Debit, Credit, OpDebit, OpCredit,   
    acc.AccountId, acc.Departmentid from  
    (SELECT am.CompanyId, am.AccountCode, am.AccountDesc, gm.accounttype,   
    GM.GroupID, GM.GroupDesc, 0 OpDr, 0 OpCr, 0 Debit, 0 Credit, 0 OpDebit , 0 OpCredit,   
   am.AccountId, d.DaDepartmentid Departmentid  
    FROM aaccountmaster AM, aGroupMaster GM, adeptAccounts d  
    WHERE GM.GroupID = AM.GroupID   
    AND GM.CompanyID = AM.CompanyID   
    AND AM.CompanyID = @intcompanyid   
    and am.accountid = d.daAccountid  
    and am.companyid = d.dacompanyid  
    and d.daDepartmentId in  (Select DeptId from #SubDepts1)    
    union all  
    SELECT am.CompanyId, am.AccountCode, am.AccountDesc, gm.accounttype,   
    GM.GroupID, GM.GroupDesc, 0 OpDr, 0 OpCr, 0 Debit, 0 Credit, 0 OpDebit , 0 OpCredit,   
    am.AccountId, deptid DepartmentId  
    FROM aaccountmaster AM, aGroupMaster GM, vwGlobalAccounts vg,  #SubDepts1  
    WHERE GM.GroupID = AM.GroupID   
    AND GM.CompanyID = AM.CompanyID   
    AND AM.CompanyID = @intcompanyid   
    and am.accountid = vg.AccountId  
    and am.companyid = vg.CompanyId ) acc   
    group by acc.CompanyId,  acc.accounttype,   acc.GroupID, acc.GroupDesc, acc.AccountCode,   
    acc.AccountDesc, acc.AccountId, acc.Departmentid,   
    OpDr, OpCr, Debit, Credit, OpDebit, OpCredit order by acc.accountid asc  
  
  
 Update #TrialBal set OBDr = abs(opening.Openingamount) from (Select AccountId,   
 DepartmentId, CompanyId,   
 case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount from   
 aaccountfinyearopening where   
 Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where   
 opening.Accountid = #TrialBal.AccountId and   
 opening.DepartmentId = #TrialBal.DepartmentId  
 and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId  
 and (((#TrialBal.ACType = 'A' or #TrialBal.ACType = 'E' ) and   
 opening.Openingamount >0) or ((#TrialBal.ACType = 'L' or #TrialBal.ACType = 'I' ) and   
 opening.Openingamount <0))  
  
 Update #TrialBal set OBCr = abs(opening.Openingamount) from (Select AccountId,   
 DepartmentId, CompanyId,   
 case when @bitCons = 1 then Openingamount else OpeningDepamount End Openingamount   
 from aaccountfinyearopening where   
 Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where   
 opening.Accountid = #TrialBal.AccountId and   
 opening.DepartmentId = #TrialBal.DepartmentId  
 and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId  
 and (((#TrialBal.ACType = 'A' or #TrialBal.ACType = 'E' ) and   
 opening.Openingamount <0) or ((#TrialBal.ACType = 'L' or #TrialBal.ACType = 'I' ) and   
 opening.Openingamount >0))  
  
 Update #TrialBal set OBDr = OBDr + isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId,   
 case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and   
 trialDeb.DepartmentId = #TrialBal.DepartmentId  
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
 Update #TrialBal set OBCr = OBCr + isnull(trialDeb.amount,0) from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId,   
 case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From   
 #vwJournalDetails v , #TempJournalHeader h where v.JournalCredit = 1 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and   
 trialDeb.DepartmentId = #TrialBal.DepartmentId  
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId   
  
 Update #TrialBal set OBCr = OBCr - OBDr, OBDr =0 Where OBCr > OBDr   
  
 Update #TrialBal set OBDr = OBDr - OBCr, OBCr = 0 Where OBDr > OBCr   
  
 Update #TrialBal set DebitAmt = trialDeb.amount from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId,   
 case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 0 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and   
 trialDeb.DepartmentId = #TrialBal.DepartmentId  
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
 Update #TrialBal set CreditAmt = trialDeb.amount from (Select v.AccountId,   
 v.DepartmentId, v.CompanyId,   
 case When @BitCons = 1 then Sum(isnull(v.Amount,0)) else   
 Sum(isnull(v.DepAmount,0)) End Amount From   
 #vwJournalDetails v, #TempJournalHeader h where v.JournalCredit = 1 and   
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and   
 h.JournalDate >= @dtFROMDate and h.JournalDate <= @dtToDate   
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where   
 trialDeb.Accountid = #TrialBal.AccountId and   
 trialDeb.DepartmentId = #TrialBal.DepartmentId  
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId  
  
    /*SELECT * FROM #TrialBal    
    where (isnull(obcr, 0)+  isnull(obdr, 0) + isnull(debitamt, 0) + isnull(creditamt, 0)) <> 0  
    ORDER BY AcType, AccCode */  
  
    SELECT CompanyID, AccCode , AccDesc, AcType, GroupID, GroupName , sum(OBDr),  
 sum(OBCr), sum(DebitAmt), sum(CrEDitAmt), sum(OpDebit), sum(OpCredit),  
 AccountId , min(Departmentid) FROM #TrialBal    
   Group By CompanyID, AccCode , AccDesc, AcType, GroupID, GroupName, AccountId    
   having (sum(isnull(obcr, 0))+  sum(isnull(obdr, 0)) + sum(isnull(debitamt, 0)) +   
   sum(isnull(creditamt, 0))) <> 0  
  
   ORDER BY AcType, AccCode  
  
      
    drop table #SubDepts1  
    drop table #vwJournalDetails  
    drop table #Tempjournalheader  
    Drop Table #TrialBal    
    set nocount on  
    set ansi_warnings on  
end  

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_071
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'spTrialBalanceNew' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE spTrialBalanceNew
end
GO
--modified by  : Hariharan       
--Modified Date  : 22/04/2004      
--Comments   : v3 (given depamount instead of amount on bitcon=0 else part)      
--   : used temporary tables for getting data after fetching for first time      
--   : Corrected the opening debit and credit balances and net balance made corrected      
--***************************************************************************************************************************      
--Modified By   : Shinu      
--Modified Date  : 26/05/2008        
--Comments   : Corrected to Get Total Amount      
--***************************************************************************************************************************              
--RefNo-1    
--Modified By : Yogesh Joe    
--Modified On : 05-06-2010    
--Comments : The report were showing wrong figure if the 'from date' is not the start date of a financial year.Now Corrected.    
--***************************************************************************************************************************   
--Ref.No:2  
--Modifted By:Shine Das  
--Modified On:09/03/2012    
--Reason     : Even if there is data available in posting tables, it is showing "No Data To Print"   
--Message if there is no enrty existing in table "aAccountFinYearOpening". (Reports like Balance Sheet, Trial Balance etc.).   
--It has to be corrected.  
--***************************************************************************************************************************
CREATE proc dbo.spTrialBalanceNew @strFROMDate as varchar(10), @strToDate as varchar(10),       
@intcompanyid as int, @intdepartmentid as int, @bitcons as bit,      
@intconsolidation as int=0  as      
set ansi_Warnings off      
set nocount on      
begin      
      
declare @dtFROMDate as datetime      
declare @dtToDate as datetime,      
 @intFinId as int,       
 @dtPrevFinUnclosedSDate as datetime,       
 @dtLastFinUnclosedEDate as datetime,       
 @intCount as int,       
 @intLastFinId as int      
      
Create table #vwJournalDetails(companyid int,      
journalid int,      
journaldetailid int,      
journalcredit bit,      
accountid int,      
Amount numeric(18,2),      
ActualAmount numeric(18,2),      
departmentid int,      
depamount numeric(18,2),       
Postgroup int)      
      
Create table #Tempjournalheader      
      
(JournalID int,      
CompanyID int,      
JournalDate smalldatetime,       
ReferenceNo varchar(100),       
Remarks varchar(250),      
Type char(10),       
Cancel bit,       
Realised bit,       
CurrencyId int,       
FinancialID int,       
chequedate datetime,       
updatetime datetime,       
bankdate datetime)      
      
Create table #vwjournalparticulars      
 (companyid int,      
 journalid int,      
 journalcredit bit,       
 particulars varchar(250))      
      
      
Create table #TrialBal(      
 CompanyID int,      
 DepartmentId int,      
 DepartmentName varchar(100),       
 accountid int,      
 AccCode varchar(50),       
 AccDesc varchar(100),      
 AcType varchar(1),      
 GroupID int,      
 GroupName varchar(100),      
 Debit numeric(18,2),      
 Credit numeric(18,2),       
 OpDebit numeric(18,2),       
 OpCredit Numeric(18,2),      
 OpBal numeric(18,2))      
      
      
Create table #TrialBalNew(      
 CompanyID int,      
 accountid int,      
 AccCode varchar(50),       
 AccDesc varchar(100),      
 AcType varchar(1),      
 GroupID int,      
 GroupName varchar(100),      
 Debit numeric(18,2),      
 Credit numeric(18,2),       
 OpDebit numeric(18,2),       
 OpCredit Numeric(18,2),      
 OpBal numeric(18,2))      
      
      
 SELECT @dtFROMDate = convert(datetime, @strFROMDate)      
 SELECT @dtToDate = convert(datetime,@strToDate)      
       
       
 Select @intFinId = financialid from vwfinyearperiod       
        where convert(datetime,@strFROMDate,101) between sdate and edate      
      
 select @dtLastFinUnclosedEDate = dateadd(dd, -1, @dtFromDate )      
      
 select @intCount = count(*) from aAccountfinyearOpening where       
 CompanyId = @intCompanyId and FinancialId = @intFinId      
      
 Select @intLastFinId = max(FinancialId) from aAccountFinYearOpening       
 where CompanyId = @intCompanyId       
       
 --if @intLastFinId = 0     --Ref.No:2   Commented
 if ISNULL(@intLastFinId,0) = 0  --Ref.No:2 Added
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod      
  where financialid = (Select min(financialid) from afinancialyear where      
  companyid = @intCompanyId ) and CompanyId= @intCompanyId      
 ELSE      
  Select  @dtPrevFinUnclosedSDate = sdate from vwFinYearPeriod      
  where financialid = @intLastFinId and CompanyId= @intCompanyId      
        
 -- create the temporary table to insert sub departments      
    -- table name is given as #SubDepts1 to avoid conflicts        -- with #SubDepts inside the sp      
    create table #SubDepts1(DeptId int)       
    if @intconsolidation=0       
             insert into #SubDepts1 values(@intDepartmentId)      
    else      
    -- get the sub depts into the temporary table      
         insert into #SubDepts1      
        Exec spSelectAllSubDepartments @intDepartmentId, @intCompanyId      
      
 insert #Tempjournalheader       
 Select H.* from moajournalheader h (NOLOCK) where JournalDate>= @dtPrevFinUnclosedSDate       
 and JournalDate <=@dtToDate and h.CompanyId = @intCompanyId      
 if @intDepartmentId = 0      
 begin      
 insert #vwJournalDetails      
 Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where       
 JournalDate>= @dtPrevFinUnclosedSDate and JournalDate <=@dtToDate and       
 h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and       
 h.CompanyId = @intCompanyId        
 end      
 else      
 begin      
 insert #vwJournalDetails      
 Select d.* from #Tempjournalheader h (NOLOCK), vwJournalDetails  d (NOLOCK) where       
 JournalDate>= @dtPrevFinUnclosedSDate and JournalDate <=@dtToDate and       
 h.JournalId = d.JournalId and h.CompanyId = d.CompanyId and h.Cancel = 0 and       
 h.CompanyId = @intCompanyId and d.departmentid in (Select Deptid from #SubDepts1)       
 end      
      
 insert #vwjournalparticulars      
 Select d.* from #Tempjournalheader h (NOLOCK), vwJournalParticulars  d (NOLOCK)       
 where h.JournalId = d.JournalId and h.CompanyId = d.CompanyId      
 and h.Cancel = 0 and h.CompanyId = @intCompanyId       
      
 insert into #TrialBal(CompanyID, DepartmentId, DepartmentName, accountid, AccCode,       
 AccDesc, AcType, GroupID, GroupName , Debit, Credit, OpBal, OpDebit, OpCredit )       
 Select a.CompanyId, m.DepartmentId, DepartmentName, a.AccountId, a.AccountCode,       
 a.AccountDesc,  g.AccountType, g.GroupID, g.GroupDesc, 0 Debit, 0 Credit, 0 OpBal,       
 0, 0 From aAccountMaster a, aGroupMaster g, aDepartmentMaster m where       
 a.GroupId = g.GroupID and a.CompanyId = g.CompanyId and a.companyid = m.companyid       
 and a.CompanyId = @intCompanyid      
      
      
 Update #TrialBal set OpBal = opening.Openingamount from (Select AccountId,       
 DepartmentId, CompanyId, case when @bitcons = 1 then Openingamount else       
 OpeningDepamount End Openingamount from aaccountfinyearopening where       
 Financialid = @intLastFinId and CompanyId = @intCompanyId) opening Where       
 opening.Accountid = #TrialBal.AccountId and       
 opening.DepartmentId = #TrialBal.DepartmentId      
 and opening.CompanyId = #TrialBal.CompanyID and opening.CompanyId = @intCompanyId      
      
 Update #TrialBal set OpBal  = OpBal + trialDeb.amount from (Select v.AccountId,       
 v.DepartmentId, v.CompanyId, case when @bitcons = 1 then       
 Sum(isnull(v.Amount,0)) else  Sum(isnull(v.DepAmount,0)) End Amount From       
 #vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and       
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and       
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate       
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where       
 trialDeb.Accountid = #TrialBal.AccountId and       
 trialDeb.DepartmentId = #TrialBal.DepartmentId      
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId      
 and (#TrialBal.AcType ='A' or #TrialBal.AcType ='E')      
      
 Update #TrialBal set OpBal  = OpBal - trialDeb.amount from (Select v.AccountId,       
 v.DepartmentId, v.CompanyId, case when @bitcons = 1 then       
 Sum(isnull(v.Amount,0)) else  Sum(isnull(v.DepAmount,0)) End Amount From       
 #vwJournalDetails v, MoaJournalHeader h where v.JournalCredit = 0 and       
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and       
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate       
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where       
 trialDeb.Accountid = #TrialBal.AccountId and       
 trialDeb.DepartmentId = #TrialBal.DepartmentId      
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId      
 and (#TrialBal.AcType ='L' or #TrialBal.AcType ='I')      
      
      
 Update #TrialBal set OpBal  = OpBal + trialDeb.amount from (Select v.AccountId,       
 v.DepartmentId, v.CompanyId, case when @bitcons = 1 then       
 Sum(isnull(v.Amount,0)) else  Sum(isnull(v.DepAmount,0)) End Amount From       
 #vwJournalDetails v , MoaJournalHeader h where v.JournalCredit = 1 and       
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and       
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate       
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where       
 trialDeb.Accountid = #TrialBal.AccountId and       
 trialDeb.DepartmentId = #TrialBal.DepartmentId      
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId      
 and (#TrialBal.AcType ='L' or #TrialBal.AcType ='I')      
      
 Update #TrialBal set OpBal  = OpBal - trialDeb.amount from (Select v.AccountId,       
 v.DepartmentId, v.CompanyId, case when @bitcons = 1 then       
 Sum(isnull(v.Amount,0)) else  Sum(isnull(v.DepAmount,0)) End Amount From       
 #vwJournalDetails v , MoaJournalHeader h where v.JournalCredit = 1 and       
 h.JournalId = v.JournalId and h.CompanyId = v.CompanyId and       
 h.JournalDate >= @dtPrevFinUnclosedSDate and h.JournalDate <= @dtLastFinUnclosedEDate       
 group by v.AccountId, v.DepartmentId, v.CompanyId) trialDeb Where       
 trialDeb.Accountid = #TrialBal.AccountId and       
 trialDeb.DepartmentId = #TrialBal.DepartmentId      
 and trialDeb.CompanyId = #TrialBal.CompanyID and trialDeb.CompanyId = @intCompanyId      
 and (#TrialBal.AcType ='A' or #TrialBal.AcType ='E')      
  
--RefNo-1-----------------Starts----------------------------------------------------  
--RefNo-1(a)  
--Below values are already added to Opening.Hence clearing the values to avoid it from   
--cosidering again.    
Update #vwJournalDetails SET Amount=0,depamount=0 FROM #Tempjournalheader h    
INNER JOIN #vwJournalDetails d ON h.JournalID=d.JournalID    
WHERE    
h.JournalDate>= @dtPrevFinUnclosedSDate AND h.JournalDate <= @dtLastFinUnclosedEDate    
--RefNo-1------------------Ends-----------------------------------------------------    
       
 Delete #TrialBal from  (Select #TrialBal.AccountId, #TrialBal.DepartmentId from       
 #TrialBal left outer join #vwJournalDetails      
 on #TrialBal.accountid = #vwJournalDetails.accountid and       
 #TrialBal.Departmentid = #vwJournalDetails.Departmentid       
 where #vwJournalDetails.DepartmentId is null) novalue      
 where #TrialBal.accountid = novalue.accountid and       
 #TrialBal.Departmentid = novalue.Departmentid and #TrialBal.opbal=0      
       
      
 if @intdepartmentid = 0       
 Begin      
      
 insert #TrialBalNew      
 Select CompanyID, accountid, AccCode, AccDesc, AcType, GroupID, GroupName,       
 sum(isnull(Debit,0)), sum(isnull(Credit,0)),       
 sum(isnull(OpDebit,0)), sum(isnull(OpCredit,0)),       
 sum(isnull(OpBal,0)) from #TrialBal      
 Group By CompanyID, accountid, AccCode, AccDesc,       
 AcType, GroupID, GroupName      
      
 select jh.companyid, jh.journalid, month(jh.journaldate) tmonth, jh.journaldate,       
 jh.referenceno, jp.particulars, am.accountcode, am.accountdesc,  case when       
  convert(int, jd.JournalCredit)  =0 then case when @bitCons = 1 then sum(amount)       
 Else sum(DepAmount) End else 0 end debitamt, case when  convert(int, jd.JournalCredit)  =1 then 'To'      
 else 'By' end as Prefix, case when   convert(int, jd.JournalCredit)  =1 then       
 case when @bitCons = 1 then sum(amount) Else sum(DepAmount) End else 0 end creditamt,      
 case when ((opBal>0 and (t.AcType='A' or t.AcType='E'))   or      
 (opBal<0 and (t.AcType='L' or t.AcType='I')))  then abs(opBal) else 0 end openingdr ,       
 case when ((opBal<0 and (t.AcType='A' or t.AcType='E'))   or      
 (opBal>0 and (t.AcType='L' or t.AcType='I'))) then abs(opBal) else 0 end openingCr      
 from #TrialBalNew t left outer join  #vwJournalDetails jd on t.companyid =       
 jd.companyid and t.accountid  = jd.accountid --and t.departmentid = jd.departmentid      
 and  @intcompanyid = jd.companyid left outer join #Tempjournalheader jh on       
 jd.companyid = jh.companyid and jd.journalid = jh.journalid  and 0 = jh.cancel        
 left outer join #vwjournalparticulars jp on jd.companyid  = jp.companyid and       
 jd.journalid = jp.journalid  and jd.journalcredit = abs(1 - jp.journalcredit) and       
-- @dtFROMDate <= JH.JournalDate AND @dtToDate >= JH.JournalDate  and   --RefNo-1(c)    
 (jh.financialid > 0 or jh.FinancialId is null), aaccountmaster am  where       
 am.companyid = t.companyid and am.accountid = t.accountid     
 Group By jh.companyid, jh.journalid, jh.journaldate, jh.referenceno,       
 jp.particulars, am.accountcode, am.accountdesc, t.AcType, /* amount, depamount,Shinu 26052008 @simdi*/ opBal,      
  convert(int, jd.JournalCredit)       
 End      
 Else      
 Begin      
      
 insert #TrialBalNew      
 Select CompanyID, accountid, AccCode, AccDesc, AcType, GroupID, GroupName,       
 sum(isnull(Debit,0)), sum(isnull(Credit,0)),       
 sum(isnull(OpDebit,0)), sum(isnull(OpCredit,0)),       
 sum(isnull(OpBal,0)) from #TrialBal where      
 DepartmentId in (Select Deptid from #SubDepts1)       
 Group By CompanyID, accountid, AccCode, AccDesc,       
 AcType, GroupID, GroupName      
      
 select jh.companyid, jh.journalid, month(jh.journaldate) tmonth, jh.journaldate,       
 jh.referenceno, jp.particulars, am.accountcode, am.accountdesc,  case when       
  convert(int, jd.JournalCredit)  = 0 then case when @bitCons = 1 then sum(amount) Else sum(DepAmount) End else 0 end debitamt,       
 case when  convert(int, jd.JournalCredit)  =1 then 'To' else 'By' end as Prefix,       
 case when  convert(int, jd.JournalCredit)  =1 then case when @bitCons = 1 then sum(amount) Else sum(DepAmount) End else 0 end creditamt,      
 case when ((opBal>0 and (t.AcType='A' or t.AcType='E'))   or      
 (opBal<0 and (t.AcType='L' or t.AcType='I')))  then abs(opBal) else 0 end openingdr ,       
 case when ((opBal<0 and (t.AcType='A' or t.AcType='E'))   or      
 (opBal>0 and (t.AcType='L' or t.AcType='I'))) then abs(opBal) else 0 end openingCr       
 from #TrialBalNew t left outer join  #vwJournalDetails jd on t.companyid =       
 jd.companyid and t.accountid  = jd.accountid --and t.departmentid = jd.departmentid      
 and  @intcompanyid = jd.companyid left outer join #Tempjournalheader jh on       
 jd.companyid = jh.companyid and jd.journalid = jh.journalid  and 0 = jh.cancel        
 left outer join #vwjournalparticulars jp on jd.companyid  = jp.companyid and       
 jd.journalid = jp.journalid  and jd.journalcredit = abs(1 - jp.journalcredit) and       
-- @dtFROMDate <= JH.JournalDate AND @dtToDate >= JH.JournalDate  and --RefNo-1(c)      
 (jh.financialid > 0 or jh.FinancialId is null), aaccountmaster am  where       
 am.companyid = t.companyid and am.accountid = t.accountid     
 --and t.DepartmentId in (Select Deptid from #SubDepts1)       
 Group By jh.companyid, jh.journalid,       
 jh.journaldate, jh.referenceno, jp.particulars, am.accountcode, am.accountdesc,       
 t.AcType, /* amount, depamount,--- Shinu 26052008 @simdi*/ opBal, convert(int, jd.JournalCredit)       
 End      
    drop table #TrialBal      
    drop table #SubDepts1      
    drop table #vwJournalDetails      
    drop table #Tempjournalheader       
end      
set nocount off      
set ansi_Warnings on        

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

------------------------------------------------------------                                      
--Modified by   : Hariharan R, Hariharan       
--Modified date : 06/03/2004, 20/03/2004                                          
--Comments : added shopid and location wise                                          
--  : given parameter to exclude from invoice for edit mode invoices --                                          
------------------------------------------------------------                                      
-- Modified by : Regin                                      
-- Modified on : 17-08-2010                                      
-- Modification:                                      
--   Added dept condition [a.departmentid= @intlocationid]                                      
--   to find the credit allotted in a given department.                                      
-- Reference   : RefNo-1                                      
------------------------------------------------------------                                      
-- Modified by : Regin                                      
-- Modified on : 18-08-2010                                      
-- Modification:                                      
--   Considered Credit Limit Type in Package Settings.                                      
-- Reference   : RefNo-2                                      
------------------------------------------------------------                                      
-- Modified by : VinothMurugan V.                                      
-- Modified on : 27-10-2010                                      
-- Modification:                                      
--   Checking overdue customers.                                      
-- Reference   : RefNo-3                                      
------------------------------------------------------------                                 
-- Modified by : Nidheesh P V                                    
-- Modified on : 24-03-2011                                      
-- Modification: Commented the part for checking No Credit For Overdue Customers and                            
-- added new code for this case.                        
-- And modified the method to find the debtor balance of the customer                         
-- using spdebtoragesum instead of vwcustomerledger.                        
-- Reference   : RefNo-4                                   
------------------------------------------------------------                            
-- Modified by : Nidheesh P V                                    
-- Modified on : 28-03-2011                                      
-- Modification: Added new parameter @numDebitbalanceIn.                      
--If NoCreditForOverdueCustomer then debtor amount of the customer is calculated                       
--in the sp spCreditForOverdueCustomers already.So this debtor amount is passed                       
--to this sp in order to avoid the compiling of spdebtoragesum once more and to                       
--speed up the process.                      
--Here @numDebitbalanceIn is optional and if this parameter is not given while executing                      
--this sp debtor amount is calculated in this sp.If numDebitbalanceIn is not null then                      
--spdebtoragesum is not executed in this sp.                      
-- Reference   : RefNo-5                                   
--------------------------                
--@chCreditLimitType-->denotes the credit limit level of the customer.                
--@CheckMode-->From where the invoice is generated(shop invoice or hq invoice).                
------------------------------------------------------------             
---altered by : shine       
-- on : 28.7.2011      
--Comment: When added to VSS unwanted commented happaned. so cleared it.        
      
---Ref -6              
---altered by : shine       
-- on : 15.10.2011      
--Comment: Setting @numDebitbalanceIn=Null cause error. So Null replaced with 0 (FOR FOCUS)      
           
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCustomerCreditLimitExceeds]') AND type in (N'P', N'PC'))
BEGIN
	DROP PROCEDURE spCustomerCreditLimitExceeds
END
GO                               
CREATE PROC dbo.spCustomerCreditLimitExceeds                                           
 @intCompanyID  as int,                                           
 @intCustomerID  as int,                        
 @CheckMode as char(1),---denotes from where this invoice is generated                 
 @intLocationID as int=0,                                          
 @dtInvDate as datetime,                              
 @numInvoiceAmt  as numeric(18,2),                                           
 @ExcludeInvAmt as numeric(18,2) =0,                   
 --@numDebitbalanceIn  as numeric(18,2)=null --RefNo-5              
  @numDebitbalanceIn  as numeric(18,2)=0 --Ref -6                                     
                                           
as                  
 Declare @numCreditLimit as numeric (18,2),                                          
 @numDebitBal as numeric (18,2),                                                        
---------------------------------------RefNo-3                                                
 @dtintdatecon as varchar(10),                                      
 @intCustomerIDcon as varchar(1000),                                      
-----------------------------------                                             
 @intDept as int,                  
 @chCreditLimitType as char(1)                    
---------------------------------------------RefNo-3                                    
declare @tempDebtorage as table ( invamt numeric(18,2),settleamt numeric(18,2),invoiceid int,                                                                    
customerid int,shopid int,due  varchar(7),invoicedate datetime ,                                                                    
invoiceno varchar(50),type varchar(20),remarks varchar(1000),customername varchar(100),                                            
currencyname varchar(50),symbol varchar(50),duedate datetime,                                                                     
overduedays int, address1 varchar(50), address2 varchar(50), address3 varchar(50),                                                                     
referenceno varchar (100),debtoraccid int,accountdesc varchar(100),CustomerCategory varchar(100),CurrencyID int)                                            
 ------------------------------------------------------                                         
begin                  
SET NOCOUNT ON                                            
 SET @numCreditLimit = 0                                          
 SET @numDebitBal  = 0                                                
 ------------------------------------------------------------------------- RefNo-3                                                            
  -- Get credit limit type and override the parameter                                      
  -- (S-Shopwise, D-Deptwise, C-Companywise) (RefNo-2)                                      
select @chCreditLimitType=isnull(CreditLimitType,'S') from aPackageSettings                                       
                    
 --If shop credit limit level is set and a hq invoice is selected then it checks as company level credit limit.                   
if @chCreditLimitType='S' and @CheckMode='D'                   
begin                  
  set @chCreditLimitType='C'                   
end                
              
if @chCreditLimitType='S'              
begin              
-- Get customer credit limit from shop customer details----              
   SELECT @numCreditLimit = CreditLimit FROM  aShopCustomerDetails                                           
   WHERE ShopID = @intLocationID and customerID = @intCustomerID                 
end                 
else              
begin --(@chCreditLimitType='C' or 'D')              
    -- Get customer credit limit from customer master-----                                     
   SELECT @numCreditLimit = CreditLimit FROM  aCustomerMaster                                            
   WHERE CustomerID = @intCustomerID                  
end                   
          
--If hq invoice is selected then it checks the credit limit in customer master.          
--If this credit limit in customer master is zero no need to check the credit limit          
if @CheckMode='C' or @CheckMode='D'  and @numCreditLimit=0        
begin           
SELECT 0                              
RETURN 0            
end             
                               
IF @numDebitbalanceIn = NULL ---RefNo-5  --Ref -6         
                    
BEGIN                             
 -- **** METHOD 1: SHOP-WISE ****                                      
 -- Check if check mode is SHOP-WISE credit limit checking.                       
 -- In shop-wise credit limit checking, the credit in given shop                                       
 -- cannot exceeding set credit limit for the shop.                
  ----RefNo-4 ------------                    
                                    
  if @chCreditLimitType='S' and @CheckMode='S'                   
  --If shop credit limit level is set and shop invoice is selected then this will executed.                                       
  begin                   
    -- Get customer credit limit from shop customer details----                                      
   SELECT @numCreditLimit = CreditLimit FROM  aShopCustomerDetails                                           
   WHERE ShopID = @intLocationID and customerID = @intCustomerID                                  
   --Get Debit Amount-----                       
   INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,0,0,@intlocationid,'',''--shopwise                            
   SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0) FROM @tempDebtorage                            
   --SELECT @numDebitbal,@numCreditLimit                          
  end                              
                                                           
  -- **** METHOD 2: DEPARTMENT-WISE ****                                      
  --If Department credit limit level is set then this will executed.                                       
  if @chCreditLimitType='D'                   
  begin                       
    -- Get customer credit limit from customer master-----                                     
   SELECT @numCreditLimit = CreditLimit FROM  aCustomerMaster                                            
   WHERE CustomerID = @intCustomerID                   
                                    
   if @CheckMode='S'                   
   begin                  
    SELECT @intDept=DepartmentID from ashops where ShopID=@intlocationid                            
   end                  
   else if @CheckMode='D'                  
   begin                  
   SELECT @intDept=@intlocationid                            
   end                  
   --Get Debit Amount------                  
   INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,@intDept,0,0,'',''--Deptwise                            
   SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0) FROM @tempDebtorage                            
   --SELECT @numDebitbal                              
  end                              
                                                
  -- **** METHOD 3: COMPANY-WISE ****                                      
  --If Company credit limit level is set then this will executed.                                       
  if @chCreditLimitType='C'                                         
  begin                  
    -- Get customer credit limit from customer master--                                    
   SELECT @numCreditLimit = CreditLimit FROM  aCustomerMaster                                            
   WHERE CustomerID = @intCustomerID                   
   --Get Debit Amount---                                 
   INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,0,0,0,'',''--Comwise                            
   SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0) FROM @tempDebtorage                            
   ---SELECT @numDebitbal                              
  end                       
END                      
ELSE                      
BEGIN                      
SET @numDebitbal=@numDebitbalanceIn ---RefNo-5                        
END                                       
----RefNo-4 ------------        
            
if (@numDebitbal + @numINvoiceamt - @ExcludeInvAmt) > @numCreditLimit and @numCreditLimit >0                                  
begin                                
SELECT 1                            
RETURN 1                                          
end                                    
else                                
begin                                
SELECT 0                              
RETURN 0                                
end                       
 ------------------RefNo-4---------------                             
                            
 ----SELECT @numdebitbal = @numdebitbal - @numCreditBal                                 
                                  
   --------RefNo-4-------------                              
 ------------else                                       
                                    
 ------------begin                                    
 ------------      SELECT @numDebitbal , @numINvoiceamt,@numCreditLimit            
 ------------  ------------------------------------------------------------------------- RefNo-3                                         
 ------------   --here checking  pending invoice against the customer( having settings in package settings)                                             
 ------------   set @NoCreditForOverdueCustomers = (select isnull(NoCreditForOverdueCustomers,0) from apackagesettings)                                            
 ------------   if @NoCreditForOverdueCustomers = 1                                             
 ------------   begin                                            
 ------------    set @dtintdatecon = convert (varchar(10),@dtInvDate,120)                                        
 ------------    set @intCustomerIDcon = cast(@intCustomerID as varchar(1000))                                        
                                              
 ------------    -- set @dtintdatecon = cast (@dtInvDate as varchar(50),120)                                       
                                            
 ------------   insert into #temp                                              
 ------------   exec spDebtorAgeSum '',@dtintdatecon,@intCustomerID,0,0 ,0,'',''                                       
 ------------   set @intdue = (select count(*) from #temp where duedate < @dtInvDate )                                            
                                                  
 ------------    if @intdue > 0   -- having any pending dues against the customer                                            
 ------------   begin                                              
 ------------    SELECT 1                                             
 ------------    return 1                                        
 ------------   end                            
 ------------    else                                      
 ------------   begin                                              
 ------------    SELECT 0                                             
 ------------    return 0                                        
 ------------   end                                            
 ------------   end                                       
 ------------     else                                         
 ------------  -------------------------------------------------------------------------                           
 ------------  begin                                          
 ------------   SELECT 0       
 ------------   return 0                                          
 ------------  end                                      
 ------------  end                                      
 --------------------RefNo-4-------------                     
 SET NOCOUNT OFF                              
end 

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_030
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwShopBincardAuditSummary]    Script Date: 03/27/2012 11:49:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spMag_GenerateVwShopBincardAuditSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spMag_GenerateVwShopBincardAuditSummary]
GO


/****** Object:  StoredProcedure [dbo].[spMag_GenerateVwShopBincardAuditSummary]    Script Date: 03/27/2012 11:49:30 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- ===============================================      
-- Author      : Regin T.      
-- Create Date : 03-08-2010      
-- Description :       
-- Generates vwShopBincardAuditSummary with hardcoded summary date.  
--  It is found that hardcoded date improves the performance of the view.  
--  This view is created to increase the speed of calculating item stock.  
-- ===============================================   
-- Referenc No  : Ref-No1          
-- Modified by	: MANUNADH.U      
-- Modified on	: 26/03/2012              
-- Comments     : Add the condition to filter local purchase bill with lphConfirmed=1
-- ===============================================
CREATE PROC [dbo].[spMag_GenerateVwShopBincardAuditSummary]  
    @strSummaryDate as varchar(8)  
AS  
BEGIN  
 -- Since a variable cannot store more than 8000 chars,   
 -- the query is directly executed using EXEC command.  
  
    EXEC (  
'IF EXISTS ( SELECT * FROM SYSOBJECTS WHERE XTYPE=''V'' AND NAME=''vwShopBincardAuditSummary'')  
DROP VIEW vwShopBincardAuditSummary')  
  
 EXEC (  
'-- =============================================================================  
-- This view was automatically generated   
-- by spMag_GenerateVwShopBincardAuditSummary.  
-- Alter above proc to make any change in this view.  
-- =============================================================================   
-- Author      : Regin T.  
-- Create Date : 03-08-2010  
-- Description :   
--    This view was created based on vwShopBincardAudit.  
--    Summary Date filtering was added additionally.  
--    Group By clause was removed to improve performance.  
--    This view is used to compute item stock in Transactions Summary method.  
-- =============================================================================        
CREATE VIEW vwShopBincardAuditSummary AS                              
          
SELECT h.gahshopid ShopId, d.gaditemid ItemId, h.gaharrivaldate sDate,                               
NULL TransNo, NULL TransId,                                
d.gadItemGoodQuantityArrived TransQty,                               
''Arrival From Godown'' [Type], 1 Mode, NULL UpdateTime, NULL CostPrice,                               
NULL DepCostPrice, NULL ConCostPrice           
FROM losgoodsarrivaltoshopheader h, losgoodsarrivaltoshopdetail d   
WHERE h.gaharrivalid=d.gadarrivalid and h.gahshopid=d.gadshopid and h.gahcancelled=0 and                               
h.gahtransfinished=1 and h.gaharrivaldate>'''+@strSummaryDate+'''         
                              
--GOODS RETURN TO SHOPS FROM CREDIT INVOICES                              
UNION ALL                              
                              
SELECT grn.grnhShopid, grd.GRNDItemID, GrnhGoodsreturnnoteDate,                              
NULL, NULL, GRNDQuantity, ''Goods Return'', 1 as mode,   
NULL, NULL, NULL, NULL          
from LosGoodsReturnNoteHeader grn, LosGoodsReturnNoteDetail grd                              
where grn.GrnhGoodsreturnnoteID = grd.GRNDReturnNoteID and grn.grnhShopid =                               
grd.GRNDShopid and GrnhCancel=0 and GRNDDamaged=0 and GrnhGoodsreturnnoteDate>'''+@strSummaryDate+'''                              
                              
union all                              
                              
--transfer in                              
select h.tihshopid,  d.tiditemid, h.tihdate, NULL, NULL,                               
d.TIDrecievedgoodqty, ''Transfer In'', 1 mode,                               
NULL, NULL, NULL, NULL  
from lostransferinheader h, lostransferindetail d where h.tihid=d.tidid and                               
h.tihshopid=d.tidshopid and h.tihcancel=0 and h.tihtransfinished=1        
and h.tihdate>'''+@strSummaryDate+'''        
                              
union all                              
                              
--recovery add                              
select sr.srshopid, sr.sritemid, sr.srdate, NULL, NULL,                                                   
sum(sr.sraddstock) as recAdd, ''Recovery Plus'', 1 Mode,   
NULL, NULL, NULL, NULL  
from                               
losstockrecovery sr       
where sr.srdate>'''+@strSummaryDate+'''          
group by  sr.srshopid, sr.srdate, sr.srid, sr.sritemid  
having isnull(sum(sr.sraddstock),0) >0                              
                              
union all                              
                              
--stock verification add                              
select svdshopid, svdItemid, svhDate, NULL, NULL,                               
svdVerifiedStock-svdAvailStock as svAddQty,                               
''Verification Plus'', 1 mode, NULL, NULL, NULL, NULL                                
from  losstockverificationheader, losstockverificationdetail where                              
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock                   
and svhCancelled=0 and  left(svhFutureVc, 1) <> ''t''        
and svhDate>'''+@strSummaryDate+'''                                 
                        
union all                              
                              
--TOTAL stock verification add                              
select svdshopid, svdItemid, svhDate, svhno, svhid,                               
svdVerifiedStock-svdAvailStock as svAddQty,                               
''Verification Plus'', 1 mode, NULL, NULL, NULL, NULL  
from  losstockverificationheader, losstockverificationdetail where                              
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock > svdAvailStock                              
and svhCancelled=0 and  left(svhFutureVc, 2) = ''tc''        
and svhDate>'''+@strSummaryDate+'''          
                                    
union all                              
                              
--exchange in                              
select sehShopID, seditemid, sehExchangeDate, NULL, NULL,                                
sedExchangeQty, ''Exchanged In'',1 mode, NULL, NULL, NULL, NULL  
FROM losposexchangeheader, losposexchangedetail where sedExchangeid=sehExchangeID                               
and sedShopID=sehShopid and sedBillorExchange=''B'' and SEHCANCELLED=0                              
and isnull(sedExchangeQty,0) >0          
and sehExchangeDate>'''+@strSummaryDate+'''                          
                              
union all                              
                              
--local purchase                              
select lphShopid,lpditemid,lphbilldate,NULL,NULL,lpdItemQuantity,''Local Purchase'',1 mode,NULL,NULL,NULL,NULL                                  
from loslocalpurchasedetail, loslocalpurchaseheader   
where lphBillId=lpdBillID and lphShopID= lpdShopid and lphCancelled=0 and lphbilldate>'''+@strSummaryDate+'''       
	and lphConfirmed=1--<<Ref-No1>>
                              
union all                              
                              
--write off                              
select wh.whshopid, wd.wditemid, wh.whdate, NULL, NULL,                               
wd.wdWriteoffQty, ''Write off'', -1 mode, NULL, NULL, NULL, NULL                               
from loswriteoffheader wh, loswriteoffdetail wd                              
where wh.whid=wd.wdid and wh.whshopid=wd.wdshopid and wh.whcancelled=0       
and wh.whdate>'''+@strSummaryDate+'''          
                              
union all                              
                              
--Deapatch                              
select dd.dgdshopid, dd.dgditemid, dh.dghDate, NULL, NULL,                               
dd.dgddespatchedgoodqty, ''Despatch To Godown'' TYpe, -1 mode,  
NULL, NULL, NULL, NULL                             
from mesdespatchtogodownheader dh, mesdespatchtogodowndetail dd                               
where dh.dghid=dd.dgdid and dh.dghshopid=dd.dgdshopid and dh.dghcancelled=0                 
and dghtransfinished = 1 -- for the concept of stock updation after transaction finish         
and dh.dghDate>'''+@strSummaryDate+'''                            
                             
union all                              
                              
--Transferout                              
select todshopid, toditemid, tohDate, NULL, NULL,                               
todissuedgoodqty, ''Transfer Out'',-1 mode, NULL, NULL, NULL, NULL                               
from mestransferoutheader , mestransferoutdetail  where                              
tohid=todid and Tohshopid=todshopid and tohcancelled=0                              
and tohtransfinished = 1 -- for the concept of stock updation after transaction finish         
and tohDate>'''+@strSummaryDate+'''                            
                              
union all                              
                              
--recovery minus                              
select sr.srshopid, sr.sritemid, sr.srdate, NULL, NULL,                             
sum(sr.srdedstock) as recAdd, ''Recovery Minus'',-1 Mode,   
NULL, NULL, NULL, NULL from                               
losstockrecovery sr        
where sr.srdate>'''+@strSummaryDate+'''         
group by  sr.srshopid, sr.srdate, sr.srid, sr.sritemid   
having sum(isnull(sr.srdedstock,0)) >0                              
                              
union all                              
                       
--stockverification minus                              
select svdshopid, svdItemid, svhDate, NULL, NULL,                               
svdAvailStock-svdVerifiedStock, ''Verification Minus'', -1 mode,  
NULL, NULL, NULL, NULL                                
from  losstockverificationheader, losstockverificationdetail where                              
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock                              
and svhCancelled=0 and  left(svhFutureVc, 1) <> ''t''         
and svhDate>'''+@strSummaryDate+'''        
                        
union all                              
                              
--Total stockverification minus                              
select svdshopid, svdItemid, svhDate, NULL, NULL,                               
svdAvailStock-svdVerifiedStock, ''Verification Minus'', -1 mode,  
NULL, NULL, NULL, NULL                        
from  losstockverificationheader, losstockverificationdetail where                              
svhid = svdid and svhshopid = svdshopid and svdVerifiedStock < svdAvailStock                              
and svhCancelled=0 and  left(svhFutureVc, 2) = ''tc''           
and svhDate>'''+@strSummaryDate+'''      
                      
union all                              
                              
--pos sales                              
select poshShopID, posditemid, poshBilldate, NULL, NULL,                               
posdquantity, ''Cash Sales'', -1 mode, NULL, NULL, NULL, NULL  
from losposdetail,losposheader                               
where poshBillid=posdBillid and poshShopid=posdshopid AND POSHCANCELLED=0        
and poshBilldate>'''+@strSummaryDate+'''       
                              
union all                              
                              
--credit invoice                              
select IhShopid, iditemid, ihInvoicedate, NULL, NULL,                                
idquantity, ''Credit Sales'', -1 mode, NULL, NULL, NULL, NULL                               
from losinvoicedetail,losinvoiceheader                              
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and ihproforma=0                              
and ihType =''I''           
and ihInvoicedate>'''+@strSummaryDate+'''      
                           
union all                              
                              
--exchange out                              
select sehShopID, seditemid, sehExchangeDate, NULL, NULL,                                
sedquantity, ''Exchange Out'', -1 mode, NULL, NULL, NULL, NULL  
from losposexchangeheader,losposexchangedetail where sedExchangeid=sehExchangeID                               
and sedShopID=sehShopid and sedBillorExchange=''E'' and SEHCANCELLED=0         
and sehExchangeDate>'''+@strSummaryDate+'''       
                              
union all         
                              
--special invoice return to shop                              
select IhShopid, iditemid, ihInvoicedate, NULL, NULL,  
-reqqty, ''Special Invoice Return'', 1 mode, NULL, NULL, NULL, NULL  
from losspecialinvoicedetail, losspecialinvoiceheader                              
where ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and idratetype=1                              
and ihproforma=0 and ihTransFinished = 1         
and ihInvoicedate>'''+@strSummaryDate+'''        
                              
union all                              
                              
select serinvhShopid, repinvdpartsid, serinvhdate, NULL, NULL,                                
repinvdqty, ''Parts Replaced'', -1 as mode, NULL, NULL, NULL, NULL  
from losinvoicedpartsreplacedetails, losserviceinvheader where serinvhid = repinvinvoiceid                                
and serinvhshopid = repinvdshopid AND serinvhcancelled=0        
and serinvhdate>'''+@strSummaryDate+'''                             
                              
union all                              
                               
--Re-Exporting                              
select rehShopID, reditemid,  rehExportDate, NULL, NULL,                              
redquantity, ''Re-Export'', -1 mode, NULL, NULL, NULL, NULL  
from losexportdetail, losexportheader                              
where rehExportID = redExportID and rehShopID = redShopID AND rehCancelled = 0 and rehproforma=0                              
and rehType=''I''          
and rehExportDate>'''+@strSummaryDate+'''       
                       
union all                        
                      
--MerGing minus                        
select lsdShopID, lsdItemID, lshDate, NULL, NULL,                          
sum(lsdqty), ''Merging Deduct'', -1 as mode, NULL, NULL, NULL, NULL  
from losMergeDetails md, losMergeHeader mh                         
where md.lsdid = mh.lshid                         
and md.lsdShopid = mh.lshShopId                         
and lshCancelled=0          
and lshDate>'''+@strSummaryDate+'''        
group by lsdShopID, lsdItemID, lshDate, lshid  
Having Sum(lsdQty) <> 0                         
                        
union all                        
                      
--MerGing Add                        
select lsdShopID, lshItemID, lshDate, NULL, NULL,                          
sum(lsdqty), ''Merging Add'', 1 as mode, NULL, NULL, NULL, NULL  
from losMergeDetails md, losMergeHeader mh                         
where md.lsdid = mh.lshid                         
and md.lsdShopID = mh.lshShopid                         
and lshCancelled = 0        
and lshDate>'''+@strSummaryDate+'''           
group by lsdShopID, lshItemID, lshDate, lshid  
Having Sum(lsdQty) <> 0               
               
union all                        
                        
--Purchase Return                        
select Ph.whshopid, Pd.wditemid, Ph.whdate, NULL, NULL,                         
Pd.wdPurchaseReturnQty, ''Purchase Return'', -1 mode, NULL, NULL, NULL, NULL  
from losPurchaseReturnheader Ph, losPurchaseReturndetail Pd                        
where Ph.whid=Pd.wdid and Ph.whshopid=Pd.wdshopid and Ph.whcancelled=0 and Ph.whtransfinished=1         
and Ph.whdate>'''+@strSummaryDate+'''        
                    
union all                              
                             
--Warrenty Claim/Business promotion                                 
select wchShopID, wcditemid, wchdate, NULL, NULL,                               
wcdQty, ''WC/BP'', -1 mode, NULL, NULL, NULL, NULL  
from losWarrentyClaimDetail,losWarrentyClaimHeader                               
where wchID=wcdID and wchShopid=wcdshopid AND WCHCANCELLED=0        
and wchdate>'''+@strSummaryDate+'''         
                             
union all                            
                            
-----Hire Purchase Invoice                            
select hpqhShopid,hpqdItemId,hpqhQuotationDate, NULL, NULL,          
1 as Qty, ''Hire Purchase'', -1 mode, NULL, NULL, NULL, NULL  
from loshpInvoiceDetail,losHpInvoiceHeader where hpqdQuotationid=hpqhQuotationID and hpqdShopid=hpqhShopid and                            
hpqhCancel=0 and hpqhType=''I''        
and hpqhQuotationDate>'''+@strSummaryDate+'''')  
  
END


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_030
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


--Modified by   : Hariharan R, Hariharan       
--Modified date : 06/03/2004, 20/03/2004                                          
--Comments : added shopid and location wise                                          
--  : given parameter to exclude from invoice for edit mode invoices --                                          
------------------------------------------------------------                                      
-- Modified by : Regin                                      
-- Modified on : 17-08-2010                                      
-- Modification:                                      
--   Added dept condition [a.departmentid= @intlocationid]                                      
--   to find the credit allotted in a given department.                                      
-- Reference   : RefNo-1                                      
------------------------------------------------------------                                      
-- Modified by : Regin                                      
-- Modified on : 18-08-2010                                      
-- Modification:                                      
--   Considered Credit Limit Type in Package Settings.                                      
-- Reference   : RefNo-2                                      
------------------------------------------------------------                                      
-- Modified by : VinothMurugan V.                                      
-- Modified on : 27-10-2010                                      
-- Modification:                                      
--   Checking overdue customers.                                      
-- Reference   : RefNo-3                                      
------------------------------------------------------------                                 
-- Modified by : Nidheesh P V                                    
-- Modified on : 24-03-2011                                      
-- Modification: Commented the part for checking No Credit For Overdue Customers and                            
-- added new code for this case.                        
-- And modified the method to find the debtor balance of the customer                         
-- using spdebtoragesum instead of vwcustomerledger.                        
-- Reference   : RefNo-4                                   
------------------------------------------------------------                            
-- Modified by : Nidheesh P V                                    
-- Modified on : 28-03-2011                                      
-- Modification: Added new parameter @numDebitbalanceIn.                      
--If NoCreditForOverdueCustomer then debtor amount of the customer is calculated                       
--in the sp spCreditForOverdueCustomers already.So this debtor amount is passed                       
--to this sp in order to avoid the compiling of spdebtoragesum once more and to                       
--speed up the process.                      
--Here @numDebitbalanceIn is optional and if this parameter is not given while executing                      
--this sp debtor amount is calculated in this sp.If numDebitbalanceIn is not null then                      
--spdebtoragesum is not executed in this sp.                      
-- Reference   : RefNo-5                                   
--------------------------                
--@chCreditLimitType-->denotes the credit limit level of the customer.                
--@CheckMode-->From where the invoice is generated(shop invoice or hq invoice).                
------------------------------------------------------------             
---altered by : shine       
-- on : 28.7.2011      
--Comment: When added to VSS unwanted commented happaned. so cleared it.        
      
---Ref -6              
---altered by : shine       
-- on : 15.10.2011      
--Comment: Setting @numDebitbalanceIn=Null cause error. So Null replaced with 0 (FOR FOCUS)      
           
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCustomerCreditLimitExceeds]') AND type in (N'P', N'PC'))
BEGIN
	DROP PROCEDURE spCustomerCreditLimitExceeds
END
GO                               
CREATE PROC dbo.spCustomerCreditLimitExceeds                                           
 @intCompanyID  as int,                                           
 @intCustomerID  as int,                        
 @CheckMode as char(1),---denotes from where this invoice is generated                 
 @intLocationID as int=0,                                          
 @dtInvDate as datetime,                              
 @numInvoiceAmt  as numeric(18,2),                                           
 @ExcludeInvAmt as numeric(18,2) =0,                   
 --@numDebitbalanceIn  as numeric(18,2)=null --RefNo-5              
  @numDebitbalanceIn  as numeric(18,2)=0 --Ref -6                                     
                                           
as                  
 Declare @numCreditLimit as numeric (18,2),                                          
 @numDebitBal as numeric (18,2),                                                        
---------------------------------------RefNo-3                                                
 @dtintdatecon as varchar(10),                                      
 @intCustomerIDcon as varchar(1000),                                      
-----------------------------------                                             
 @intDept as int,                  
 @chCreditLimitType as char(1)                    
---------------------------------------------RefNo-3                                    
declare @tempDebtorage as table ( invamt numeric(18,2),settleamt numeric(18,2),invoiceid int,                                                                    
customerid int,shopid int,due  varchar(7),invoicedate datetime ,                                                                    
invoiceno varchar(50),type varchar(20),remarks varchar(1000),customername varchar(100),                                            
currencyname varchar(50),symbol varchar(50),duedate datetime,                                                                     
overduedays int, address1 varchar(50), address2 varchar(50), address3 varchar(50),                                                                     
referenceno varchar (100),debtoraccid int,accountdesc varchar(100),CustomerCategory varchar(100),CurrencyID int)                                            
 ------------------------------------------------------                                         
begin                  
SET NOCOUNT ON                                            
 SET @numCreditLimit = 0                                          
 SET @numDebitBal  = 0                                                
 ------------------------------------------------------------------------- RefNo-3                                                            
  -- Get credit limit type and override the parameter                                      
  -- (S-Shopwise, D-Deptwise, C-Companywise) (RefNo-2)                                      
select @chCreditLimitType=isnull(CreditLimitType,'S') from aPackageSettings                                       
                    
 --If shop credit limit level is set and a hq invoice is selected then it checks as company level credit limit.                   
if @chCreditLimitType='S' and @CheckMode='D'                   
begin                  
  set @chCreditLimitType='C'                   
end                
              
if @chCreditLimitType='S'              
begin              
-- Get customer credit limit from shop customer details----              
   SELECT @numCreditLimit = CreditLimit FROM  aShopCustomerDetails                                           
   WHERE ShopID = @intLocationID and customerID = @intCustomerID                 
end                 
else              
begin --(@chCreditLimitType='C' or 'D')              
    -- Get customer credit limit from customer master-----                                     
   SELECT @numCreditLimit = CreditLimit FROM  aCustomerMaster                                            
   WHERE CustomerID = @intCustomerID                  
end                   
          
--If hq invoice is selected then it checks the credit limit in customer master.          
--If this credit limit in customer master is zero no need to check the credit limit          
if @CheckMode='C' or @CheckMode='D'  and @numCreditLimit=0        
begin           
SELECT 0                              
RETURN 0            
end             
                               
IF @numDebitbalanceIn = NULL ---RefNo-5  --Ref -6         
                    
BEGIN                             
 -- **** METHOD 1: SHOP-WISE ****                                      
 -- Check if check mode is SHOP-WISE credit limit checking.                       
 -- In shop-wise credit limit checking, the credit in given shop                                       
 -- cannot exceeding set credit limit for the shop.                
  ----RefNo-4 ------------                    
                                    
  if @chCreditLimitType='S' and @CheckMode='S'                   
  --If shop credit limit level is set and shop invoice is selected then this will executed.                                       
  begin                   
    -- Get customer credit limit from shop customer details----                                      
   SELECT @numCreditLimit = CreditLimit FROM  aShopCustomerDetails                                           
   WHERE ShopID = @intLocationID and customerID = @intCustomerID                                  
   --Get Debit Amount-----                       
   INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,0,0,@intlocationid,'',''--shopwise                            
   SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0) FROM @tempDebtorage                            
   --SELECT @numDebitbal,@numCreditLimit                          
  end                              
                                                           
  -- **** METHOD 2: DEPARTMENT-WISE ****                                      
  --If Department credit limit level is set then this will executed.                                       
  if @chCreditLimitType='D'                   
  begin                       
    -- Get customer credit limit from customer master-----                                     
   SELECT @numCreditLimit = CreditLimit FROM  aCustomerMaster                                            
   WHERE CustomerID = @intCustomerID                   
                                    
   if @CheckMode='S'                   
   begin                  
    SELECT @intDept=DepartmentID from ashops where ShopID=@intlocationid                            
   end                  
   else if @CheckMode='D'                  
   begin                  
   SELECT @intDept=@intlocationid                            
   end                  
   --Get Debit Amount------                  
   INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,@intDept,0,0,'',''--Deptwise                            
   SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0) FROM @tempDebtorage                            
   --SELECT @numDebitbal                              
  end                              
                                                
  -- **** METHOD 3: COMPANY-WISE ****                                      
  --If Company credit limit level is set then this will executed.                                       
  if @chCreditLimitType='C'                                         
  begin                  
    -- Get customer credit limit from customer master--                                    
   SELECT @numCreditLimit = CreditLimit FROM  aCustomerMaster                                            
   WHERE CustomerID = @intCustomerID                   
   --Get Debit Amount---                                 
   INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,0,0,0,'',''--Comwise                            
   SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0) FROM @tempDebtorage                            
   ---SELECT @numDebitbal                              
  end                       
END                      
ELSE                      
BEGIN                      
SET @numDebitbal=@numDebitbalanceIn ---RefNo-5                        
END                                       
----RefNo-4 ------------        
            
if (@numDebitbal + @numINvoiceamt - @ExcludeInvAmt) > @numCreditLimit and @numCreditLimit >0                                  
begin                                
SELECT 1                            
RETURN 1                                          
end                                    
else                                
begin                                
SELECT 0                              
RETURN 0                                
end                       
 ------------------RefNo-4---------------                             
                            
 ----SELECT @numdebitbal = @numdebitbal - @numCreditBal                                 
                                  
   --------RefNo-4-------------                              
 ------------else                                       
                                    
 ------------begin                                    
 ------------      SELECT @numDebitbal , @numINvoiceamt,@numCreditLimit            
 ------------  ------------------------------------------------------------------------- RefNo-3                                         
 ------------   --here checking  pending invoice against the customer( having settings in package settings)                                             
 ------------   set @NoCreditForOverdueCustomers = (select isnull(NoCreditForOverdueCustomers,0) from apackagesettings)                                            
 ------------   if @NoCreditForOverdueCustomers = 1                                             
 ------------   begin                                            
 ------------    set @dtintdatecon = convert (varchar(10),@dtInvDate,120)                                        
 ------------    set @intCustomerIDcon = cast(@intCustomerID as varchar(1000))                                        
                                              
 ------------    -- set @dtintdatecon = cast (@dtInvDate as varchar(50),120)                                       
                                            
 ------------   insert into #temp                                              
 ------------   exec spDebtorAgeSum '',@dtintdatecon,@intCustomerID,0,0 ,0,'',''                                       
 ------------   set @intdue = (select count(*) from #temp where duedate < @dtInvDate )                                            
                                                  
 ------------    if @intdue > 0   -- having any pending dues against the customer                                            
 ------------   begin                                              
 ------------    SELECT 1                                             
 ------------    return 1                                        
 ------------   end                            
 ------------    else                                      
 ------------   begin                                              
 ------------    SELECT 0                                             
 ------------    return 0                                        
 ------------   end                                            
 ------------   end                                       
 ------------     else                                         
 ------------  -------------------------------------------------------------------------                           
 ------------  begin                                          
 ------------   SELECT 0       
 ------------   return 0                                          
 ------------  end                                      
 ------------  end                                      
 --------------------RefNo-4-------------                     
 SET NOCOUNT OFF                              
end 
Go
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--Ticket/Task ID:M_052
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--GO
use [adminv2]
GO
/****** Object:  StoredProcedure [dbo].[spPopulateHpInterestDetails]    Script Date: 05/28/2011 14:13:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spPopulateHpInterestDetails]') AND type in (N'P', N'PC'))
BEGIN
DROP PROC spPopulateHpInterestDetails
END
GO
--Created by: Nidheesh P V        
--Created on: 18/07/2010      
--Comments: To populate interest details for hp cheques      
-----------------------------------------------------------------------------
--Modified by: Nidheesh P V        
--Modified on: 18/07/2010      
--Comments: added isnull condition 
--Reference : RefNo-1     
-----------------------------------------------------------------------------
--spPopulateHpInterestDetails 2,1,168,'20100808'     
                            
CREATE proc spPopulateHpInterestDetails                                
(                                
@DepartmentID as int,                                
@CompanyID as int,                   
@ProcessId as int,                             
@AsonDate as datetime                   
)                                
as                                
declare @Nrcptdate as datetime                                
declare @NproId as int                                
declare @NProDetId as int                                
declare @NDepId as int                              
declare @NChqDate as datetime                               
declare @NCustId as int                              
declare @IntrstDate as datetime                                
declare @Count as int                                
declare @MaxProDetId as int                              
declare @TempVar table                                
(                                
ChequeDate datetime,                                
SettledDate datetime,                                
ProcessId int,                                
ProcessDetailId int,                                
Performer char(1),                                
PendingChequCount int,                                
InterestDate datetime,                                
DepId int                              
)                                
begin                                
set nocount on                              
declare newcurs cursor for        
select distinct hprhReceiptDate,hpdChequeDate,hphProcessingId,hprdProcessingDetailId,hpdDepartmentID,hphCustomerID       
from ahpprocessingdetail inner join ahpprocessingheader h      
on hpdProcessingId=hphProcessingId and hpdDepartmentID=hphDepartmentID and hpdCompanyID=hphCompanyID and hphProcessingId=@ProcessId                   
and (hphDepartmentID=@DepartmentID or @DepartmentID=0)       
inner join vwhpSettlementDetails v      
on hpdDetailID=hprdProcessingDetailId and hpdCompanyID=hprhCompanyID and hpdDepartmentID=DepartmentID       
and (hpdDepartmentID=@DepartmentID or @DepartmentID=0)                      
and ((isnull(hphreprocessaftersettlement,0)=0 and v.hprdProcessingId=h.hphProcessingId)or(hphreprocessaftersettlement=1 and v.hprdProcessingId=h.hphReferenceID))      
where isnull(hpdPosted,0)=0 and hphCancel=0 and hphAmended=0 and hpdChequedate<=@AsonDate and hpdCompanyID=@CompanyID          
--and hphProcessingId=642  RefNo-1                                
order by hphProcessingId,hprdProcessingDetailId        
open newcurs             
fetch next from newcurs into @Nrcptdate,@NChqDate,@NproId,@NProDetId,@NDepId,@NCustId                
while @@fetch_status=0                     
begin           
set @Count=(select count(*) from ahpprocessingdetail where hpdProcessingId=@NproId                                  
and  hpdChequeDate<=@Nrcptdate and hpdDetailID>=@NProDetId and hpdDepartmentID=@NDepId)                                
select @MaxProDetId=max(hprdProcessingDetailId) from vwhpSettlementDetails where hprdProcessingId=@NproId                                 
and DepartmentID=@NDepId and hprhCompanyID=@CompanyID and DepartmentID=@NDepId                              
------If count>=3 then the customer will be non performer------                                
------but Interset for the first 3 cheque should be posted as in Chequedate----             
if @Count>=3                           
begin                              
 if @NProDetId>3                              
 begin                               
  insert into @TempVar values(@NChqDate,@Nrcptdate,@NproId,@NProDetId,'N',@Count,@Nrcptdate,@NDepId)                              
 end                                
 else                                
 begin                              
  insert into @TempVar values(@NChqDate,@Nrcptdate,@NproId,@NProDetId,'P',@Count,@NChqDate,@NDepId)                              
 end            
end                              
 else                              
 begin               
  insert into @TempVar values(@NChqDate,@Nrcptdate,@NproId,@NProDetId,'P',@Count,@NChqDate,@NDepId)                               
 end                               
                            
if @MaxProDetId=@NProDetId                              
begin                                  
 if (select Performer from @TempVar where ProcessId=@NproId and ProcessDetailId=@NProDetId and DepId=@NDepId)='P'                              
  begin                            
   if (select count(*) from aHPCustomerPerfomance where hpProcessingID=@NproId)>0                               
   begin                      
    delete from aHPCustomerPerfomance where hpProcessingID=@NproId                              
   end                              
  end                              
 else                              
  begin                              
   if (select count(*) from aHPCustomerPerfomance where hpProcessingID=@NproId)<0                               
   begin                              
    insert into aHPCustomerPerfomance values(@NCustId,@NproId)                              
   end                               
  end                              
end                                
fetch next from newcurs into @Nrcptdate,@NChqDate,@NproId,@NProDetId,@NDepId,@NCustId                                
end                                 
close newcurs                              
deallocate newcurs             
select  hphProcessingNo + '-'+ cast(hpdDetailID as nvarchar)RefNo,hpCustName,                                
ChequeDate,SettledDate,ProcessId,ProcessDetailId,Performer,InterestDate,hpdInterest                              
from @TempVar left outer join                                 
ahpprocessingdetail inner join ahpprocessingheader on hphDepartmentID=hpdDepartmentID                                 
and hphProcessingID=hpdProcessingID and hphCompanyID=hpdCompanyID                                
and hphCancel=0 and hphCompanyID=@CompanyID and hphAmended=0 and (hpdDepartmentID=@DepartmentID or @DepartmentID=0)                                
on ProcessId=hpdProcessingId and ProcessDetailId=hpdDetailID and DepId=hphDepartmentID                               
left outer join losHpCustomerDetails on hphCustomerID=hpCustID and hpCompanyID=hphCompanyID                                
order by ProcessId,ProcessDetailId                              
set nocount off                              
end 
Go
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--Ticket/Task ID:M_052
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--GO
use [adminv2]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPInterest]    Script Date: 05/28/2011 14:13:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersHPInterest]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'  
    --spUpdateLEDgersHPInterest 1,2,1 ,''20070101''
-----------------------------------------------------    
--exec spUpdateLEDgersHPInterest 1,2,1      
-- Created Date  : 28/11/2007      
-- Created by  : Prasanth      
-- Comments  : For HP Processing Interest Posting      
------------------------------------------------------    
CREATE proc [dbo].[spUpdateLEDgersHPInterest] @intCompanyID as int, @intProcessingID as int, @intDetailID as int,@duedate as varchar(15)  
as       
begin      
Declare       
 @intJournalID as int,      
 @intJournalDetailID as int,      
 @intFinancialID as int,      
 @intDepartmentID as int,      
 @dtIntDate as datetime, 
 @dtChqDate as datetime,     
 @intCustomerAccID as int,       
 @intCustomerID as int,      
 @strProcessingNo as varchar(50),      
 @strRemarks as varchar(300),       
 @numAmount as numeric(18,2),       
 @dtutime as datetime,      
 @intcurrencyid as int,      
 @intSuspenseAccID as int,      
 @intInterestAccId as int      
 set nocount on 
    select             
       @intcurrencyid = CurrencyId             
    from             
       acompanymaster             
    where             
       companyid = @intcompanyid        
         
      
   /* getting the maximum Journal ID FROM journal table */      
   SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader       
   WHERE CompanyID = @intCompanyID      
      
    Select                 
       @intSuspenseAccID=SuspenseAcc ,@intInterestAccId=InterestAcc             
    from               
        ahpaccountssettings               
    where                
        companyid = @intcompanyid           
      
     set @intJournalID = @intJournalID + 1      
             
     select @intProcessingID=hphProcessingID,@strProcessingNo=hphProcessingNo + ''-''+ cast(hpdDetailID as nvarchar),      
        @dtChqDate=hpdChequeDate,@numAmount=hpdinterest,      
        @strremarks=hphRemarks,@intFinancialID=hphFinancialID,      
        @intDepartmentID=hphDepartmentID,@dtutime=hphUpdateTime      
    FROM ahpprocessingdetail left outer join ahpprocessingheader      
    on hpdprocessingID=hphProcessingID and hpdDepartmentID=hphDepartmentID and hpdCompanyID=hphCompanyID       
    WHERE hpdProcessingID=@intProcessingID and hpdDetailID=@intDetailID  --and hpdRental<=hpdSettlementAmount and hpdChequeStatus<>''B''    
       
 set @dtIntDate= convert(datetime,@duedate,101)
--set @dtDueDate=convert(datetime,@dtDueDate,101)  
   
    insert into moaJournalHeader (JournalID, CompanyID, JournalDate,       
    referenceno, remarks,financialID,Type, CurrencyID,chequedate,updatetime) values       
    (@intJournalID, @intCompanyID, @dtIntDate, @strProcessingNo,        
    @strRemarks, @intFinancialID,''HPRI'', @intcurrencyid, @dtChqDate, @dtutime)      
      
 set @intJournalDetailID = 1      
        if @intSuspenseAccID<>0       
        begin           
 /* Debeting the Interest Amount */               
 insert into moaJournalDetails               
 (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,               
 Amount, actualAmount, departmentID, depamount, PostGroup)              
 values               
 (@intJournalId, @intJournalDetailId, @intCompanyID, 0,               
 @intSuspenseAccID, @numAmount,               
 @numAmount,@intDepartmentID, @numAmount, 1)            
      
  set @intJournalDetailId = @intJournalDetailId +1              
  /* Crediting the  Interest Amount (Earned Finacial Income Earned */               
  insert into moaJournalDetails               
  (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,               
  Amount, actualAmount, departmentID, depamount, PostGroup)              
  values               
  (@intJournalId, @intJournalDetailId, @intCompanyID, 1,               
  @intInterestAccId, @numAmount,               
  @numAmount,@intDepartmentID, @numAmount, 1)        
        
 /* mark the record as postED */      
 update ahpprocessingDetail set hpdPosted =1 WHERE hpdDetailID = @intDetailID and       
        hpdProcessingID= @intProcessingID      
  end      
set nocount off 
end      
  
  ' 
END

Go
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--Ticket/Task ID:M_052
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--GO
use [adminv2]
GO
/****** Object:  StoredProcedure [dbo].[spUpdateLEDgersHPReprocessing]    Script Date: 05/28/2011 14:13:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLEDgersHPReprocessing]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'  
--spUpdateLEDgersHPReprocessing 1,2,642
-----------------------------------------------------                 
-- Created Date  : 02/31/2010                  
-- Created by  : Nidheesh P V                  
-- Comments  : For HP Re Processing Adjustment,HP Unearned income Posting                  
------------------------------------------------------                
CREATE proc [dbo].[spUpdateLEDgersHPReprocessing] @intCompanyID as int,@intDepartmentID as int,@intProcessingID as int            
as                   
begin                  
Declare                   
 @intJournalID as int,                  
 @intJournalDetailID as int,                  
 @intFinancialID as int,                  
 --@intDepartmentID as int,                          
 @strProcessingNo as varchar(50),                  
 @strRemarks as varchar(300),                   
 @dtutime as datetime,              
 @dtDate as datetime,                
 @intcurrencyid as int,                  
 @intAdjustmentAccID as int,                  
 @intInterestAccId as int,        
 @intCustomerAccID as int,           
 @CustomerId as int,                 
 @CustomerAmount as numeric(18,2),            
 @Adjustmentamnt as numeric(18,2),            
 @UnearnedIncome as numeric(18,2)         
         
            
    select                         
       @intcurrencyid = CurrencyId                         
    from                         
       acompanymaster                         
    where                         
       companyid = @intcompanyid                    
                     
                  
   /* getting the maximum Journal ID FROM journal table */                  
   SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader                   
   WHERE CompanyID = @intCompanyID                  
                     
        
    Select                             
       @intCustomerAccID =DebtorAcc ,@intAdjustmentAccID=AdjustmentAcc ,@intInterestAccId=SuspenseAcc                         
    from                           
        ahpaccountssettings                           
    where                            
        companyid = @intcompanyid                       
                  
     set @intJournalID = @intJournalID + 1                  
                         
     select @intProcessingID=hphProcessingID,@strProcessingNo=hphProcessingNo,                  
        @dtDate=hphProcessingDate, @Adjustmentamnt=hphAdjustmentAmount, @UnearnedIncome=hphBalanceInterest,                
        @strremarks=hphRemarks,@intFinancialID=hphFinancialID, @CustomerId=hphCustomerID,@dtutime=hphUpdateTime                  
    FROM ahpprocessingdetail left outer join ahpprocessingheader                  
    on hpdprocessingID=hphProcessingID and hpdCompanyID=hphCompanyID and (hphDepartmentID=@intDepartmentID or @intDepartmentID=0)                   
    WHERE hphreprocessaftersettlement=1 and hphReferenceID is not null  and hpdProcessingID=@intProcessingID and hphCompanyID =@intCompanyID           
               
    insert into moaJournalHeader (JournalID, CompanyID, JournalDate,                   
    referenceno, remarks,financialID,Type, CurrencyID,updatetime) values                   
    (@intJournalID, @intCompanyID, @dtDate, @strProcessingNo,                    
    @strRemarks, @intFinancialID,''HPRPAS'', @intcurrencyid,@dtutime)                  
      --''HPRPAS''---HP Reprocessing After Settlement            
            
set @intJournalDetailID = 1                  
if @intAdjustmentAccID<>0  and  @intInterestAccId<>0                
begin                       
             
/* Debiting Adjustment Carrying Amount in Adj. account*/           
  --(@Adjustmentamnt-@UnearnedIncome)===Adjustment Carrying Amount 
if (@Adjustmentamnt-@UnearnedIncome)>=0   
begin       
	insert into moaJournalDetails                           
	(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                           
	Amount, actualAmount, departmentID, depamount, PostGroup)                                          
	values                           
	(@intJournalId, @intJournalDetailId, @intCompanyID,0,@intAdjustmentAccID,             
	(@Adjustmentamnt-@UnearnedIncome) , (@Adjustmentamnt-@UnearnedIncome),@intDepartmentID, (@Adjustmentamnt-@UnearnedIncome), 1)             
end
else
begin
	insert into moaJournalDetails                           
	(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                           
	Amount, actualAmount, departmentID, depamount, PostGroup)                                          
	values                           
	(@intJournalId, @intJournalDetailId, @intCompanyID,1,@intAdjustmentAccID,             
	(@UnearnedIncome-@Adjustmentamnt) , (@UnearnedIncome-@Adjustmentamnt),@intDepartmentID, (@UnearnedIncome-@Adjustmentamnt), 1) 
end
               
set @intJournalDetailId = @intJournalDetailId +1              
/* Debiting  in Unearned income account */                   
insert into moaJournalDetails                           
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                       
Amount, actualAmount, departmentID, depamount, PostGroup)                          
values                           
(@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intInterestAccId,             
@UnearnedIncome,@UnearnedIncome,@intDepartmentID, @UnearnedIncome, 1)             
                       
set @intJournalDetailId = @intJournalDetailId +1              
set @CustomerAmount= @Adjustmentamnt          
        
/* Crediting against customer account */                   
insert into moaJournalDetails                           
(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                           
Amount, actualAmount, departmentID, depamount, PostGroup)                          
values                           
(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intCustomerAccID ,                                         
@CustomerAmount,@CustomerAmount,@intDepartmentID,@CustomerAmount, 1)                        
        
set @intJournalDetailId = @intJournalDetailId +1          
            
 /* mark the record as postED */                  
 update aHpProcessingHeader set hphAdjustmentPosted =1 WHERE hphProcessingID= @intProcessingID and hphDepartmentID=@intDepartmentID                   
end                  
end                  
              
          ' 
END

Go
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--Ticket/Task ID:M_084
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
GO
-----------------------------------------------------------------------------                       
--Created By : AADYAKUMAR.D.V
--Created On : 10/04/2012            
--Purpose    : Checking Active & For Sale in Kit&List Item            
-------------------------------------------------------------------------- 
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spFindInActiveItems]') AND type in (N'P', N'PC'))
BEGIN
DROP PROC spFindInActiveItems
END
GO
--spFindInActiveItemsL 1,'K'
--spFindInActiveItemsL 13,'L'  
create procedure spFindInActiveItems 
	@ID as int,@ItemType as char,
	@InactiveItems as int=0 output
as
	declare @Active as int
	declare @getActive as cursor
set @InactiveItems=0
if @ItemType='K'
	begin
		set @getActive = CURSOR  FOR 
		select case when A.Active=0 OR A.forsales=0 OR KM.Active=0 then 0 else 1 end   Active 
		from aKitItemMaster KM 
		inner join aKitItemDetail KD on KM.KitID=KD.KitID
		inner join aItem A on KD.ItemId = A.ItemID
		where KM.KitID=@ID
	end
else
	begin
		set @getActive = CURSOR  FOR 
		select case when A.Active=0 OR A.forsales=0 then 0 else 1 end Active
		from alistitemmaster LM 
		inner join alistitemdetails LD on LM.ListID=LD.ListID
		inner join aItem A on LD.ItemId = A.ItemID
		where LD.ListID=@ID
	end
open @getActive 
fetch next
from @getActive into @Active
while @@FETCH_STATUS=0
begin
if @Active=0
	 begin
		 set @InactiveItems=1
	 end
--print @Active 
fetch next
from @getActive into @Active  
end
close @getActive 
--print 'Inactive' print @InactiveItems
return @InactiveItems
deallocate @getActive

Go
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--Ticket/Task ID:M_107
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spulShopPurchReturn]    Script Date: 04/13/2012 16:54:03 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spulShopPurchReturn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spulShopPurchReturn]
GO

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spulShopPurchReturn]    Script Date: 04/13/2012 16:54:03 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--spulShopPurchReturn 1,6  
--Created  : 21/06/2008  
--Created by  : Shinu  
--Purpose : For Posting Shop Purchase Returns  
-----------------------------------------------------------------------------------------------------------------------  
--Modified  On :  
--Modified  By :  
--Comments :  
-----------------------------------------------------------------------------------------------------------------------  
CREATE proc [dbo].[spulShopPurchReturn] @intCompanyId as int, @intShopID as int as   
begin  
  Declare @intJournalID as int,@intJournalDetailID as int,@intswoid as int,@intFinancialID as int,  
	@strswoNo as varchar(50),@dtswoDate as datetime,@strRemarks as varchar(500),@intDepartmentId as int,  
	@numSwoAmt as numeric(18, 2),@intCompanyCurID as int,@intInventoryAccId as int,@intPurchRetAccid as int,  
	@dtutime as datetime,@strzerorate as varchar(1),@intFailcount as int,@numDepExRate as numeric(18, 8),  
	@numConExRate as numeric(18, 8),@intCurrencyId as int,@strExRates VarChar(250),@numAccExRate Numeric(18, 2),  
	@numTransEr Numeric(18, 2),@numAaccAmt Numeric(18, 2)  
  
  --get the companyCurrencyID   
  SELECT @intCompanyCurID = CurrencyID FROM acompanymaster WHERE CompanyId = @intCompanyId  
  select @intPurchRetAccid = PurchaseRtnAccID from aPackageSettings where CompanyId = @intCompanyId  
  select @intInventoryAccId = InventoryID,@strzerorate = substring(isnull(futurevc, ''), 1, 1)   
  from aPackageSettings   
  /* getting the maximum Journal ID FROM journal table */  
  SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader WHERE CompanyId = @intCompanyId  
  set @intJournalID = @intJournalID + 1  
  
  Declare swoCur cursor for   
  SELECT whID, whNo, whDate,  whRemarks, UpdateTime, whConExRate,whDepExRate, whDepartmentId, whExchangeRates     
  FROM losPurchaseReturnHeader WHERE whCancelled = 0 And whShopId = @intShopID And whPosted = 0 And whType ='P'  
  
  open swocur  
	fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate, @strRemarks,   
	  @dtutime, @numConExRate, @numDepExRate, @intDepartmentId, @strExRates  
	while @@Fetch_status = 0   
	begin -- cur begin  
	  select @intCurrencyId = CurrencyId from aAccountMaster where AccountId = @intInventoryAccId   
		and CompanyId = @intCompanyId  
	  exec spReturnExRate @intCurrencyId, @strExRates,@numTransEr output   
	  -- to take financialid from afinancialyear table with curfinancialyear=1 -- hari011211  
	  select @intFinancialID = financialid from vwfinyearperiod where @dtswoDate between sdate and edate  
	  -- to check the no of records with item rate =0 or null in both the detail table  
	  -- and the item master table. If so we cannot do any thing in the posting with out item rate.  
	  -- so that transaction will be avoided from posting  
	  -- hariharan 011211  
	  set @intFailcount = 0  
	  select @intFailcount = count(*) from losPurchaseReturnDetail, aItem where   
		wdID = @intswoiD and wdShopId = @intShopId and wdItemId = ItemId   
		and ( wdCostPrice =null or wdCostPrice =0) and (itemrate=0 or itemrate is null)   
	  
	  -- to allow to proceed if allow zero rate condition given - hari 020905  
	  if @strzerorate = 'z'     
		begin  
			set @intFailcount=0  
		end  
	  if @intfailcount = 0 -- for item rate = 0 check  
		begin  -- to update the item rate to the gadCostPrice     
		  update losPurchaseReturnDetail set wdCostPrice = itemrate from  aItem where ( wdCostPrice =null or 
			wdCostPrice = 0) and wdID = @intswoiD and  wdShopId = @intShopId and wdItemId = ItemId  
  
		  insert into moaJournalHeader (JournalID, CompanyId, JournalDate,referenceno, remarks, financialID, Type,
			CurrencyID,chequedate, updatetime )values (@intJournalID, @intCompanyId, @dtswoDate, @strswono,   
			@strRemarks, @intFinancialID, 'sret', @intcompanycurID, @dtswoDate, @dtutime )  
  
		  set @intJournalDetailID = 1  
		  -- getting the total amount with qty and item cost price  
		  select @numSwoAmt = isnull(sum(wdPurchaseReturnqty * wdCostPrice),0) from losPurchaseReturnDetail swod 
		  where wdShopId = @intShopId and wdid = @intswoid  
  
		  -- for converting the amount --->  
		  select @intCurrencyId = CurrencyId from aAccountMaster where AccountId = @intPurchRetAccId  
		  exec spReturnExRate @intCurrencyId, @strExRates,@numAccExRate output   
          exec spConvertCurrency @numTransEr, @numAccExRate,@numSwoAmt,@numAaccAmt output  
  
		  -- debiting the Purchase Return accid   
		  insert into moaJournalDetails (JournalID,journaldetailID,CompanyId,JournalCrEDit,AccountID,Amount,
			actualAmount,DepAmount, DepartmentId)   
		  values(@intJournalID, @intjournalDetailID, @intCompanyId,0,@intPurchRetAccid,@numSwoAmt * @numConExRate,
			@numAaccAmt,@numSwoAmt * @numDepExRate,  @intDepartmentId)   
  
		  set @intJournalDetailID = @intJournalDetailID + 1  
		  -- credit the inventory acc id  
		  insert into moaJournalDetails (JournalID,journaldetailID,CompanyId,JournalCrEDit, accountid, Amount, 
			actualamount,DepAmount, DepartmentId)   
		  values (@intJournalID, @intjournalDetailID, @intCompanyId, 1,@intInventoryAccId,@numSwoAmt * @numConExRate,
			@numSwoAmt,@numSwoAmt * @numDepExRate, @intDepartmentId )  
		
		  update losPurchaseReturnHeader set whPosted = 1 WHERE WhID = @intswoID and whShopId = @intShopId  
		  set @intJournalId = @intJournalId + 1   
		end -- for item rate = 0 check  
	  fetch next FROM  swoCur into @intswoiD, @strswono, @dtswoDate,@strRemarks, @dtutime, @numConExRate,   
		@numDepExRate, @intDepartmentId, @strExRates  
	end -- CUR END  
  Close swoCur   
  Deallocate swoCur   
end  
  
  
Go
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--Ticket/Task ID:M_129
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
GO
use adminv2;
go
if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'spCustomerArriveExDiff' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE spCustomerArriveExDiff
end
GO 
/*
-Modified on  : 14/06/2005        
--Modified by   : Hariharan R        
--Comments  : Modified the vendor selection        
--   : Removed the currencyid filteration and allowed all         
--   : customers to undergo checking, Incorporated vwCustomerledger in temp1 insertion to increase speed     
   ----modified by      : jyothish        
--modified Date     : 15/12/2011     
------------------------------------------------------------------
Reference   No : 01	
Modified	By : Shine Das
Modified	On : 13.04.2012
Comments	   : Customer Adjustment entry was wrong. 
*/
CREATE  proc spCustomerArriveExDiff         
  @intcompanyid as int, @strexrates as varchar(250),         
  @strcurdate as varchar(10),@intDepartmentID as int=0, @Depwise as char(1) ='d' as        
begin        
set nocount on        
set ansi_warnings off        
declare @intcount as int,        
 @intcustomerid as int,        
 @numdepbal as numeric(18,2),        
 @numconsbal as numeric(18,2),        
 @numresbal as numeric(18,2),        
 @strcustomername as varchar(250),        
 @intDepCurrID as int,        
 @intcusCurrID as int,        
 @intConsCurrID as int,        
 @numdepamount as numeric(18,2),        
 @numConsamount as numeric(18,2) ,        
 @straccounttype as char(1),        
 @bitjournalcredit as bit,        
 @numdiffamt as numeric(18,2),
  @numResBalInConsCurrency as numeric(18,2)         --- -- Reference   No : 01 Added new field

-- Reference   No : 01 Commented	         
--CREATE table #temp1(        
-- companyid int,        
-- customerid int,        
-- customername varchar(250),        
-- CurrencyID int,        
-- resbal numeric(18,2),         
-- consbal numeric(18,2)        
-- )        

----- Reference   No : 01 Added
	CREATE table #temp1(    
	 companyid int,    
	 customerid int,    
	 customername varchar(250),    
	 CurrencyID int,    
	 resbal numeric(18,2),     
	 consbal numeric(18,2),
	 depbal numeric(18,2)      -- Reference   No : 01 Added new field to store Department amount  
	 )    
        
CREATE table #temp2(        
 companyid int,        
 customerid int,        
 customername varchar(250),        
 DepBalance numeric(18,2),        
 consbalance numeric(18,2),        
 resbalance numeric(18,2),        
 depamount  numeric(18,2),        
 consamount  numeric(18,2),        
 journalcredit bit        
 )        
        
select @intDepCurrID =depcurrencyid from aDepartmentMaster         
 where companyid =@intcompanyid and departmentID= @intDepartmentID        
        
select @intConsCurrID = currencyID from aCompanyMaster where companyId =@intCompanyID        
-- all the customer other than company currency are taken into the temp table        
if @DepWise ='d'        
     Begin        
 insert into #temp1        
 select C.companyid, C.customerid, customername, currencyID,         
 sum(isnull(invamt,0)) - sum(isnull(pmtamt,0)),         
 sum(isnull(dinvamt,0)) - sum(isnull(dpmtamt,0)),  
 sum(isnull(dinvamt,0)) - sum(isnull(dpmtamt,0))  -- Reference   No : 01 Find Department Balance
 from acustomermaster c,        
  vwcustomerledger V        
 where c.companyid =@intcompanyid --and currencyid <> @intDepCurrID           
 AND c.customerId = v.Customerid and v.Departmentid = @intDepartmentId        
 and c.Companyid = v.CompanyId and tdate <= @strcurdate group by C.companyid, C.customerid,         
 customername, currencyID        
       
       
 --select C.companyid, C.customerid, customername, currencyID,         
 --sum(isnull(invamt,0)) - sum(isnull(pmtamt,0)),         
 --sum(isnull(dinvamt,0)) - sum(isnull(dpmtamt,0))  from acustomermaster c,        
 --ashopCustomerDetails s, vwcustomerledger V        
 --where c.companyid =@intcompanyid --and currencyid <> @intDepCurrID         
 --and c.CustomerId =s.CustomerId AND S.shopid in (Select shopid from         
 --ashops where departmentid = @intDepartmentId and companyid = @intCompanyid)        
 --AND c.customerId = v.Customerid and v.Departmentid = @intDepartmentId        
 --and c.Companyid = v.CompanyId group by C.companyid, C.customerid,         
 --customername, currencyID       
   --Jyothish commeted this code15/12/2011     
     End        
Else        
        
     Begin        
 insert into #temp1        
 			 select c.companyid, c.customerid, c.customername, c.currencyID,
			 sum(isnull(invamt,0)) - sum(isnull(pmtamt,0)),         
			 sum(isnull(cinvamt,0)) - sum(isnull(cpmtamt,0)),
			 sum(isnull(dinvamt,0)) - sum(isnull(dpmtamt,0)) -- Reference   No : 01 Find Department Balance
			 from vwCustomerLedger v inner join  
			 acustomermaster c on c.CustomerID = v.customerid  
			 where c.customerId = v.customerid and v.departmentid =@intDepartmentId
			 group by c.companyid, c.customerid, c.customername, c.currencyID
			 
			 -- Reference   No : 01 Commented; Result was wrong when run the below qry. So change made and
			 -- placed above.
				 --select c.companyid, c.customerid, customername, currencyID,         
				 --sum(isnull(invamt,0)) - sum(isnull(pmtamt,0)),         
				 --sum(isnull(cinvamt,0)) - sum(isnull(cpmtamt,0)) from acustomermaster c,        
				 --ashopCustomerDetails s, vwCustomerLedger V        
				 --where c.companyid =@intcompanyid -- and currencyid <> @intConsCurrID         
				 --and c.CustomerId =s.CustomerId AND S.shopid in (Select shopid from         
				 --ashops where departmentid = @intDepartmentId and companyid = @intCompanyid)        
				 --AND c.customerId = v.Customerid and v.Departmentid = @intDepartmentId        
				 --and c.Companyid = v.CompanyId group by C.companyid, C.customerid,         
				 --customername, currencyID        
     End        
        
        
select @intcount = count(*) from #temp1       
while @intcount <> 0        
begin -- for while        
 set @numconsbal =0.0        
 set @numresbal = 0.0         
 set @numdepbal = 0.0        
    
     -- Reference   No : 01 Commented    
 --select @intcustomerid = customerid, @strcustomername = customername,         
 --@intcusCurrID=CurrencyID, @numresbal = resbal, @numdepbal = consbal from #temp1        
 
 			 -- -- Reference   No : 01 Added Below
			  select @intcustomerid = customerid, @strcustomername = customername,     
			 @intcusCurrID=CurrencyID, @numresbal = resbal, @numdepbal = depbal, @numconsbal = consbal from #temp1  
			        
        
-- SD if @DepWise ='d'        
	exec spConvertequiamount @intcusCurrID, 'm', @intDepCurrID,         
	'm', @strexrates , @numresbal, @numdepamount output,  'r'         
-- SD else        
	exec spConvertequiamount @intcusCurrID, 'm', @intConsCurrID,         
	'm', @strexrates , @numresbal, @numResBalInConsCurrency output,  'r'         
	
 /* --     -- Reference   No : 01 Commented  
 if abs(@numdepbal - @numdepamount) >= 1 -- this has the exchange difference        
 begin        
  if (@numdepamount > @numDepbal)         
   set @bitjournalcredit =0                
  if (@numdepamount < @numDepbal)         
   set @bitjournalcredit =1        
 */  
  
       -- Reference   No : 01 Added Below
   if abs(@numconsbal - @numResBalInConsCurrency) >= 1 -- this has the exchange difference        
 begin        
  if (@numResBalInConsCurrency > @numconsbal)         
   set @bitjournalcredit =0                
  if (@numResBalInConsCurrency < @numconsbal)         
   set @bitjournalcredit =1 
   
        
 --set @numdiffamt  = abs(@numdepamount - @numDepbal)  
  set @numdiffamt  = abs(@numResBalInConsCurrency - @numconsbal)       
        
 if @DepWise ='d' -- department currency        
 Begin        
  exec spConvertequiamount @intDepCurrID, 'm', @intConsCurrID,         
  'm', @strexrates , @numdiffamt, @numConsamount output,  'r'    
             
  insert into #temp2 values         
  (@intcompanyid, @intcustomerid, @strcustomername,@numdepbal,         
  @numConsbal,@numresbal,@numdiffamt, @numConsamount, @bitjournalcredit)        
 End        
 else -- Consolidation Currency        
 Begin    
     
  exec spConvertequiamount @intConsCurrID, 'm', @intDepCurrID,         
  'm', @strexrates , @numdiffamt, @numdepamount output,  'r'    
  
       -- Reference   No : 01 Commented       
  --insert into #temp2 values         
  --(@intcompanyid, @intcustomerid, @strcustomername,@numdepbal,         
  --@numConsbal,@numresbal, @numConsamount ,@numdepamount, @bitjournalcredit)       
  
       -- Reference   No : 01 Added Below
	  insert into #temp2 values         
  (@intcompanyid, @intcustomerid, @strcustomername,@numdepbal,         
  @numConsbal,@numresbal, @numdepamount,@numdiffamt, @bitjournalcredit)  
 End        
        
 end        
 delete from #temp1 where customerid = @intcustomerid        
 select @intcount = count(*) from #temp1        
end -- for while        
select * from #temp2        
set nocount off        
set ansi_warnings on        
end        
GO      
        
           
Go
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--Ticket/Task ID:M_002
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
GO
use adminv2
GO
IF EXISTS( SELECT * FROM SYSOBJECTS WHERE XTYPE='P' AND NAME='spMagnolia_GeneratePosBill')
BEGIN
	DROP PROCEDURE spMagnolia_GeneratePosBill
END	
GO

--spMagnolia_GeneratePosBill 8,3
------------------------------------------------------------   
--CREATED BY: Nidheesh                
--CREATED ON: 06-04-2011                
--COMMENTS: TO GENERATE THE POS BILLID,BILLNO FOR ALL SHOPS    
--THE LOGIC TO GENERATE BILLID,BILLNO IS DONE AS LIKE IN THE FRONT END CODE.        
------------------------------------------------------------   
-- RefNo.1
-- Modified By : Bijesh.B
-- Modified on : 09-08-2011
-- Ticket id   : OCB-808128 (Pos Bill No. repeating) 
------------------------------------------------------------   
-- RefNo.2
-- Modified By : Shine Das
-- Modified on : 17-04-2012
-- Ticket id   : M_002 (Magnolia_Issue Tracking System) 
------------------------------------------------------------   
CREATE PROC spMagnolia_GeneratePosBill
(
@intshopId AS INT,
@intCounterId AS INT,
@strBillNo AS VARCHAR(30)='' OUTPUT,
@intBillID AS INT ='' OUTPUT
)
AS
DECLARE @Prefix as varchar(50)                          
DECLARE @NumberFound  AS INT 
DECLARE @intNextBillID AS INT
DECLARE @intNextBillNo AS INT          
BEGIN
SET NOCOUNT ON
----TO GET PREFIX OF THE SHOP-------         
SELECT @Prefix=Prefix 
FROM aPrefix p INNER JOIN aFinancialYear f ON p.Financialid=f.FinancialId               
WHERE CurFinancialYear=1 AND InterfaceId=1502 AND ShopId=@intShopId   
-------------------------------------

-----FOR NO COUNTER SHOPS-----      
IF @intCounterId = 0         
BEGIN          
	SELECT @NumberFound = count(LastBillNo) 
	FROM losPosHeaderLastBillNo WHERE ShopId=@intShopId              
	IF @NumberFound > 0              
	BEGIN  ---IF LASTBILLNO IS IN losPosHeaderLastBillNo THEN IT DIRECTLY TAKES THESE FROM THE TABLE  
		
	/* -- RefNo.1 start commented below

		SELECT @intNextBillNo=LastBillNo + 1
		FROM losPosHeaderLastBillNo WHERE ShopId=@intShopId   
	    
	    UPDATE losPosHeaderLastBillNo 
	    SET LastBillNo = @intNextBillNo WHERE ShopId=@intShopId                             
	
	*/ 
		UPDATE losPosHeaderLastBillNo SET LastBillNo = LastBillNo + 1 WHERE ShopId=@intShopId                             
		SELECT @intNextBillNo=LastBillNo FROM losPosHeaderLastBillNo WHERE ShopId=@intShopId

	-- RefNo.1 ends
	
	END              
	ELSE              
	BEGIN ---IF LASTBILLNO IS NOT IN losPosHeaderLastBillNo THEN IT TAKES THESE FROM THE losposheader TABLE    
		/*  -- RefNo.2	           
	   SELECT @intNextBillNo = ISNULL(MAX(CONVERT(INT,RIGHT(poshBillNo,LEN(poshBillNo)-LEN(CONVERT(VARCHAR,@Prefix))))),0) + 1               
	   FROM losposheader WHERE poshShopId=@intShopId AND LEFT(poshbillno,len(@Prefix))=@Prefix AND poshCounterId=0                         
	   INSERT INTO losPosHeaderLastBillNo(ShopId, LastBillNo) VALUES(@intShopId, @intNextBillNo)              
	   */
	
	/*  -- RefNo.2	Altered Above section as given Below. Above Section causes Conversion error when counterwise
	    transaction has disabled after doing counterwise transactions. 
	*/  --  START
	
	SELECT @intNextBillNo = ISNULL(MAX(CONVERT(INT,REVERSE(LEFT((REVERSE(poshBillNo)),(PATINDEX('%/%' ,(REVERSE (poshBillNo))))-1)))),0) + 1                   
    FROM losposheader WHERE poshShopId=@intShopId AND LEFT(poshbillno,len(@Prefix))=@Prefix AND poshCounterId=0                             
    INSERT INTO losPosHeaderLastBillNo(ShopId, LastBillNo) VALUES(@intShopId, @intNextBillNo)  
    -- RefNo.2	END
    
	END   
SET @intBillID = (SELECT CASE WHEN COUNT(poshBillid)=0 THEN 1 ELSE MAX(poshBillid)+1 END FROM losposheader WHERE poshShopID=@intShopId)  
SET @strBillNo = @Prefix+CONVERT(VARCHAR,@intNextBillNo)
END -----FOR NO COUNTER SHOPS-----   
ELSE          
BEGIN -----FOR COUNTER SHOPS-----   
SELECT @NumberFound=COUNT(NextBillNo)
FROM aCounterMaster WHERE CounterShopId=@intshopId AND counterid=@intCounterId             
	IF @NumberFound >0 
	BEGIN            
		SELECT @intNextBillID = NextBillId,@intNextBillNo = NextBillNo 
		FROM aCounterMaster WHERE CounterShopId=@intshopId AND counterid=@intCounterId             
			IF @intNextBillID IS NOT NULL           
			BEGIN   ---IF NextBillId,NextBillNo IS IN aCounterMaster THEN IT DIRECTLY TAKES THESE FROM THE TABLE  
				UPDATE aCounterMaster SET NextBillId = @intNextBillID+1,NextBillNo=@intNextBillNo+1 
				WHERE CounterShopId=@intshopId AND counterid=@intCounterId                              
			END              
			ELSE              
			BEGIN  ---IF NextBillId IS NULL IN aCounterMaster THEN IT DIRECTLY TAKES NextBillId FROM THE TABLE aSettings     
				Select @intNextBillID=RefBillId From aSettings 
				IF @intNextBillID IS NOT NULL 
				BEGIN
					UPDATE aCounterMaster SET NextBillId = @intNextBillID+1,NextBillNo=@intNextBillNo+1 
					WHERE CounterShopId=@intshopId AND counterid=@intCounterId                               
				END
			END   
	SET @intBillID = CONVERT(INT, CAST(100 + @intCounterId AS VARCHAR) + CAST (@intNextBillID AS VARCHAR))
	SET @strBillNo = @Prefix+'C'+CONVERT(VARCHAR,@intCounterId)+'/'+CONVERT(VARCHAR,@intNextBillNo)  
	END
END -----FOR COUNTER SHOPS-----  
--SELECT @strBillNo
--SELECT @intBillID
SET NOCOUNT OFF
END
GO                   

Go
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--Ticket/Task ID:M_095
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT * FROM SYSOBJECTS WHERE TYPE='P' AND name ='spMag_GetShopItemPrice')
BEGIN
DROP PROC spMag_GetShopItemPrice
END

GO
  
--CREATED BY : NIDHEESH P V        
--CREATED ON : 01/08/2011        
--COMMENTES : TO GET SHOP ITEM DETAILS INCLUDING PRICE LIST(CAN MODIFY FOR MORE DETAILS)        
--MODIFIED AREA : RPTITEMPRICELIST    
----------------------------------------------------------------------    
--REF.NO:1
--MODIFIED BY : AADYAKUMAR.D.V        
--MODIFIED ON : 17/04/2012        
--COMMENTES : FILTER ITEMS WITH SEGMENT PREICE

--spMag_GetShopItemPrice 1,1,2,'',0,'',0,0,1       
        
CREATE proc spMag_GetShopItemPrice(@IntCompId as int,@IntDeptId as int,@IntShopId as int,     
   @strItemCate as varchar(max)='',@IntItemID as int=0,@strBrand as varchar(max)='',
   @Intactive as int=0,@IntStock as int=0,
   @IntSegmentid as int=0--REF.NO:1
   )        
AS        
BEGIN        
SET NOCOUNT ON;  
with cteShopItems(ShopID,shopname,ItemID,ItemCode,itemdescri,Part_code,brand,PackingTypeName,PackingTypeid,        
  costprice,sellingPrice,WholesalePrice,DiscountPrice,Symbol,selectorder)        
as     
(        
select asd.ShopID,s.shopname,asd.ItemID,ItemCode,vsd.itemdescri,Part_code,vsd.brand,vsd.PackingTypeName,ssd.PackingTypeid,        
    convert(numeric(18,2),(vsd.ItemRate*vsd.Quantity)) as costprice,ssd.sellingPrice,ssd.WholesalePrice,ssd.DiscountPrice,cm.Symbol,       
    row_number()over(partition by ssd.PackingTypeid,ssd.itemid,asd.ShopID order by ssd.shopid desc) as selectorder        
FROM        
    ashopitemdetail asd         
    INNER JOIN vwShopItemStockitemsItemDtls vsd ON asd.itemid = vsd.ItemID         
    AND (asd.shopid=@IntShopId OR @IntShopId=0) AND (ItemCategoryID in (@strItemCate) OR @strItemCate='')         
    AND (vsd.ItemID=@IntItemID OR @IntItemID=0) AND (brand in (@strBrand) or @strBrand='') and ((@Intactive=0 and 0=0) or (@Intactive=1 and vsd.active=1))       
 INNER JOIN losShopItemShipmentDetail ssd ON ssd.itemid=asd.itemid AND ssd.PackingTypeid=vsd.packingtypeid AND companyid=@IntCompId        
 AND ((ssd.shopid is null AND 0=0) OR (ssd.shopid is not null AND ssd.shopid=asd.shopid))
 and ( ssd.segmentid = @IntSegmentid or @IntSegmentid=0 ) --REF.NO:1       
 INNER JOIN acurrencymaster cm on cm.currencyid=ssd.currencyid        
 INNER JOIN  aShops s ON asd.shopid = s.ShopID        
 LEFT OUTER JOIN vwInquiryShopStock vs ON  @IntStock=1 and vs.shopid=asd.shopid and vs.itemid=asd.itemid and vs.stock>0  
)
select * from cteShopItems where selectORder=1 ORder by shopname        
SET NOCOUNT OFF        
        
END

-------------------------------------


Go
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--Ticket/Task ID:
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
GO

IF EXISTS( SELECT * FROM SYSOBJECTS WHERE XTYPE='P' 
AND NAME='spInventoryforcat_adv')
BEGIN
	DROP PROCEDURE spInventoryforcat_adv
END
GO

       
--spInventoryforcat_adv 1,0,'27','250','20100110'          
          
/*            
        
CREATED BY  : NIDHEESH P V          
CREATED ON  : 15-02-2010            
CREATED FOR : NEED TO GET ADVANCE INVENTORY FORCAT REPORT. RHIS PROCEDURE WILL RETURN LAST 30DAYS SALES PLUS QUATERILY AVARAGE SALES PLUS EXTRA.            
USAGE     :             
            
*/            
-------------------------------------            
CREATE PROCEDURE spInventoryforcat_adv            
(            
 @CompanyID AS INT,            
 @DepartmentID AS INT,            
 @strCategoryID AS VARCHAR(500),            
 @strItemID AS VARCHAR(500),        
 @Date AS varchar(10)         
            
)            
AS            
SET NOCOUNT ON    
BEGIN            
declare           
@dtDate as datetime,        
@startdate as datetime,          
@enddate as datetime,          
@STR as varchar(max),          
@STR1 as varchar(max)          
        
--set @dtDate= convert(datetime,@Date)         
set @dtDate = cast (@Date as datetime)        
        
 --print @dtDate        
select @STR1='a.ItemDescription,a.Part_code,a.itemcode,d.dname,c.CategoryNameDescription,v.* from ( select vw.Itemid,sum(VW.PreviousMonth)PreMonthSum,        
sum(Last3MonthAvg)Last3MonthAvg, sum(Last6MonthAvg)Last6MonthAvg,sum(Last12MonthAvg)Last12MonthAvg,sum(Last24MonthAvg)Last24MonthAvg,'          
SELECT @STR1=ISNULL(@STR1,'')+'SUM('+'DAY'+CONVERT(VARCHAR,DAY(TDATE))+')'+ 'DAY' + CONVERT(VARCHAR,DAY(TDATE)) + ',' + CONVERT(VARCHAR,DAY(TDATE))+ 'H' + CONVERT(VARCHAR,DAY(TDATE)) + ',' FROM  fnMakeDateTable(@dtDate,1)          
SELECT @STR1=SUBSTRING(@STR1,1,LEN(@STR1)-1)+' From ('          
             
select @STR='Select Itemid,sum(PreviousMonth)PreviousMonth,sum(Last3MonthAvg)Last3MonthAvg, sum(Last6MonthAvg)Last6MonthAvg,        
sum(Last12MonthAvg)Last12MonthAvg,sum(Last24MonthAvg)Last24MonthAvg,'          
SELECT @STR=ISNULL(@STR,'')+'          
 CASE WHEN DAY(StockDate)='+ CONVERT(VARCHAR,DAY(TDATE))+' THEN SUM(AsonSale) END '+''''+ 'DAY' + CONVERT(VARCHAR,DAY(TDATE))+''''+ ' ,'  FROM  fnMakeDateTable(@dtDate,1)          
SELECT @STR=SUBSTRING(@STR,1,LEN(@STR)-1)          
          
CREATE TABLE #ItemDetail            
(            
 ItemID INT,            
 CompanyID INT,            
 DepartmentID INT,            
 SHOPID INT,            
 CategoryID INT,            
 Description VARCHAR(200),            
 BinLocation VARCHAR(50),            
 StockDate DATETIME,            
 SlNo INT,            
 AsonSale NUMERIC(18,2),          
 PreviousMonth NUMERIC(18,2),          
 Last3MonthAvg NUMERIC(18,2),        
 Last6MonthAvg NUMERIC(18,2),        
 Last12MonthAvg NUMERIC(18,2),        
 Last24MonthAvg NUMERIC(18,2)        
)            
            
            
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,StockDate,SlNo,AsonSale)             
SELECT posdItemID,CompanyID,DepartmentID,poshShopId,Tdate,SlNo,sum(isnull(Quantity,0)) Qty FROM fnMakeDateTable(@dtDate,1) left outer join             
vwSalesAnalysisByItem on  TDate=poshBillDate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,',')) or @strCategoryID='')--AND posdItemID=@strItemID         
inner join ashops on poshShopId=ShopID  and CompanyID=@CompanyID  and (DepartmentID= @DepartmentID or @DepartmentID=0)      
group by posdItemID,poshShopId,Tdate,SlNo,DepartmentID ,CompanyID           
          
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,PreviousMonth)          
select posdItemID,CompanyID,DepartmentID,poshShopId,sum(isnull(Quantity,0))Qty from vwSalesAnalysisByItem v         
inner join ashops on poshShopId=ShopID  and CompanyID= @CompanyID  and (DepartmentID= @DepartmentID or @DepartmentID=0)      
where year(poshBillDate)=YEAR(DATEADD(m, -1, @dtDate))and month(poshBillDate)=MONTH(DATEADD(m, -1, @dtDate)) AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,',')) or @strCategoryID='')--and posdItemID=@strItemID         
group by posdItemID,poshShopId,DepartmentID,CompanyID          
---Lst3monthsAvg----        
set @startdate= dateadd(m,-3,@dtDate)        
set @enddate= dateadd(m,-1,@dtDate)        
set @startdate= dbo.ufn_GetFirstDayOfMonth(@startdate)        
set @enddate= dbo.ufn_GetLastDayOfMonth(@enddate)        
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,Last3MonthAvg)          
select posdItemID,CompanyID,DepartmentID,poshShopId,(sum(isnull(Quantity,0))/3)Qty from vwSalesAnalysisByItem v         
inner join ashops on poshShopId=ShopID and CompanyID= @CompanyID and (DepartmentID= @DepartmentID or @DepartmentID=0)        
where poshBillDate>= @startdate and poshBillDate<= @enddate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,',')) or @strCategoryID='') --and posdItemID=@strItemID         
group by posdItemID,poshShopId,DepartmentID,CompanyID          
        
---Lst6monthsAvg----        
set @startdate= dateadd(m,-6,@dtDate)        
set @enddate= dateadd(m,-1,@dtDate)        
set @startdate= dbo.ufn_GetFirstDayOfMonth(@startdate)        
set @enddate= dbo.ufn_GetLastDayOfMonth(@enddate)        
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,Last6MonthAvg)          
select posdItemID,CompanyID,DepartmentID,poshShopId,(sum(isnull(Quantity,0))/6)Qty from vwSalesAnalysisByItem v         
inner join ashops on poshShopId=ShopID and CompanyID= @CompanyID and (DepartmentID= @DepartmentID or @DepartmentID=0)       
where poshBillDate>= @startdate and poshBillDate<= @enddate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,',')) or @strCategoryID='') --and posdItemID=@strItemID         
group by posdItemID,poshShopId,DepartmentID,CompanyID          
        
---Lst12monthsAvg----        
set @startdate= dateadd(m,-12,@dtDate)        
set @enddate= dateadd(m,-1,@dtDate)        
set @startdate= dbo.ufn_GetFirstDayOfMonth(@startdate)        
set @enddate= dbo.ufn_GetLastDayOfMonth(@enddate)        
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,Last12MonthAvg)          
select posdItemID,CompanyID,DepartmentID,poshShopId,(sum(isnull(Quantity,0))/12)Qty from vwSalesAnalysisByItem v         
inner join ashops on poshShopId=ShopID and CompanyID= @CompanyID and (DepartmentID= @DepartmentID or @DepartmentID=0)        
where poshBillDate>= @startdate and poshBillDate<= @enddate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,',')) or @strCategoryID='') --and posdItemID=@strItemID         
group by posdItemID,poshShopId,DepartmentID,CompanyID          
        
---Lst24monthsAvg----        
set @startdate= dateadd(m,-24,@dtDate)        
set @enddate= dateadd(m,-1,@dtDate)        
set @startdate= dbo.ufn_GetFirstDayOfMonth(@startdate)        
set @enddate= dbo.ufn_GetLastDayOfMonth(@enddate)        
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,Last24MonthAvg)          
select posdItemID,CompanyID,DepartmentID,poshShopId,(sum(isnull(Quantity,0))/24)Qty from vwSalesAnalysisByItem v         
inner join ashops on poshShopId=ShopID and CompanyID= @CompanyID and (DepartmentID= @DepartmentID or @DepartmentID=0)        
where poshBillDate>= @startdate and poshBillDate<= @enddate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,',')) or @strCategoryID='') --and posdItemID=@strItemID         
group by posdItemID,poshShopId,DepartmentID,CompanyID          
        
exec(          
'SELECT '+ @STR1+@STR +  ' FROM #ItemDetail GROUP BY Itemid,StockDate,PreviousMonth )vw where itemid is not null Group by vw.Itemid)v         
inner join aitem a on v.ItemID=a.ItemID inner join aitemcategory c on c.ItemCategoryID=a.ItemCategoryID inner join adistributormaster d on d.did=a.did')          
 SET NOCOUNT OFF         
end          
          
----------------------------------        
        

Go
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--Ticket/Task ID:
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
GO

IF EXISTS( SELECT * FROM SYSOBJECTS WHERE XTYPE='P' 
AND NAME='spInventoryforcat_adv')
BEGIN
	DROP PROCEDURE spInventoryforcat_adv
END
GO

       
--spInventoryforcat_adv 1,0,'27','250','20100110'          
          
/*            
        
CREATED BY  : NIDHEESH P V          
CREATED ON  : 15-02-2010            
CREATED FOR : NEED TO GET ADVANCE INVENTORY FORCAT REPORT. RHIS PROCEDURE WILL RETURN LAST 30DAYS SALES PLUS QUATERILY AVARAGE SALES PLUS EXTRA.            
USAGE     :             
            
*/            
-------------------------------------            
CREATE PROCEDURE spInventoryforcat_adv            
(            
 @CompanyID AS INT,            
 @DepartmentID AS INT,            
 @strCategoryID AS VARCHAR(500),            
 @strItemID AS VARCHAR(500),        
 @Date AS varchar(10)         
            
)            
AS            
SET NOCOUNT ON    
BEGIN            
declare           
@dtDate as datetime,        
@startdate as datetime,          
@enddate as datetime,          
@STR as varchar(max),          
@STR1 as varchar(max)          
        
--set @dtDate= convert(datetime,@Date)         
set @dtDate = cast (@Date as datetime)        
        
 --print @dtDate        
select @STR1='a.ItemDescription,a.Part_code,a.itemcode,d.dname,c.CategoryNameDescription,v.* from ( select vw.Itemid,sum(VW.PreviousMonth)PreMonthSum,        
sum(Last3MonthAvg)Last3MonthAvg, sum(Last6MonthAvg)Last6MonthAvg,sum(Last12MonthAvg)Last12MonthAvg,sum(Last24MonthAvg)Last24MonthAvg,'          
SELECT @STR1=ISNULL(@STR1,'')+'SUM('+'DAY'+CONVERT(VARCHAR,DAY(TDATE))+')'+ 'DAY' + CONVERT(VARCHAR,DAY(TDATE)) + ',' + CONVERT(VARCHAR,DAY(TDATE))+ 'H' + CONVERT(VARCHAR,DAY(TDATE)) + ',' FROM  fnMakeDateTable(@dtDate,1)          
SELECT @STR1=SUBSTRING(@STR1,1,LEN(@STR1)-1)+' From ('          
             
select @STR='Select Itemid,sum(PreviousMonth)PreviousMonth,sum(Last3MonthAvg)Last3MonthAvg, sum(Last6MonthAvg)Last6MonthAvg,        
sum(Last12MonthAvg)Last12MonthAvg,sum(Last24MonthAvg)Last24MonthAvg,'          
SELECT @STR=ISNULL(@STR,'')+'          
 CASE WHEN DAY(StockDate)='+ CONVERT(VARCHAR,DAY(TDATE))+' THEN SUM(AsonSale) END '+''''+ 'DAY' + CONVERT(VARCHAR,DAY(TDATE))+''''+ ' ,'  FROM  fnMakeDateTable(@dtDate,1)          
SELECT @STR=SUBSTRING(@STR,1,LEN(@STR)-1)          
          
CREATE TABLE #ItemDetail            
(            
 ItemID INT,            
 CompanyID INT,            
 DepartmentID INT,            
 SHOPID INT,            
 CategoryID INT,            
 Description VARCHAR(200),            
 BinLocation VARCHAR(50),            
 StockDate DATETIME,            
 SlNo INT,            
 AsonSale NUMERIC(18,2),          
 PreviousMonth NUMERIC(18,2),          
 Last3MonthAvg NUMERIC(18,2),        
 Last6MonthAvg NUMERIC(18,2),        
 Last12MonthAvg NUMERIC(18,2),        
 Last24MonthAvg NUMERIC(18,2)        
)            
            
            
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,StockDate,SlNo,AsonSale)             
SELECT posdItemID,CompanyID,DepartmentID,poshShopId,Tdate,SlNo,sum(isnull(Quantity,0)) Qty FROM fnMakeDateTable(@dtDate,1) left outer join             
vwSalesAnalysisByItem on  TDate=poshBillDate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,',')) or @strCategoryID='')--AND posdItemID=@strItemID         
inner join ashops on poshShopId=ShopID  and CompanyID=@CompanyID  and (DepartmentID= @DepartmentID or @DepartmentID=0)      
group by posdItemID,poshShopId,Tdate,SlNo,DepartmentID ,CompanyID           
          
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,PreviousMonth)          
select posdItemID,CompanyID,DepartmentID,poshShopId,sum(isnull(Quantity,0))Qty from vwSalesAnalysisByItem v         
inner join ashops on poshShopId=ShopID  and CompanyID= @CompanyID  and (DepartmentID= @DepartmentID or @DepartmentID=0)      
where year(poshBillDate)=YEAR(DATEADD(m, -1, @dtDate))and month(poshBillDate)=MONTH(DATEADD(m, -1, @dtDate)) AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,',')) or @strCategoryID='')--and posdItemID=@strItemID         
group by posdItemID,poshShopId,DepartmentID,CompanyID          
---Lst3monthsAvg----        
set @startdate= dateadd(m,-3,@dtDate)        
set @enddate= dateadd(m,-1,@dtDate)        
set @startdate= dbo.ufn_GetFirstDayOfMonth(@startdate)        
set @enddate= dbo.ufn_GetLastDayOfMonth(@enddate)        
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,Last3MonthAvg)          
select posdItemID,CompanyID,DepartmentID,poshShopId,(sum(isnull(Quantity,0))/3)Qty from vwSalesAnalysisByItem v         
inner join ashops on poshShopId=ShopID and CompanyID= @CompanyID and (DepartmentID= @DepartmentID or @DepartmentID=0)        
where poshBillDate>= @startdate and poshBillDate<= @enddate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,',')) or @strCategoryID='') --and posdItemID=@strItemID         
group by posdItemID,poshShopId,DepartmentID,CompanyID          
        
---Lst6monthsAvg----        
set @startdate= dateadd(m,-6,@dtDate)        
set @enddate= dateadd(m,-1,@dtDate)        
set @startdate= dbo.ufn_GetFirstDayOfMonth(@startdate)        
set @enddate= dbo.ufn_GetLastDayOfMonth(@enddate)        
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,Last6MonthAvg)          
select posdItemID,CompanyID,DepartmentID,poshShopId,(sum(isnull(Quantity,0))/6)Qty from vwSalesAnalysisByItem v         
inner join ashops on poshShopId=ShopID and CompanyID= @CompanyID and (DepartmentID= @DepartmentID or @DepartmentID=0)       
where poshBillDate>= @startdate and poshBillDate<= @enddate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,',')) or @strCategoryID='') --and posdItemID=@strItemID         
group by posdItemID,poshShopId,DepartmentID,CompanyID          
        
---Lst12monthsAvg----        
set @startdate= dateadd(m,-12,@dtDate)        
set @enddate= dateadd(m,-1,@dtDate)        
set @startdate= dbo.ufn_GetFirstDayOfMonth(@startdate)        
set @enddate= dbo.ufn_GetLastDayOfMonth(@enddate)        
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,Last12MonthAvg)          
select posdItemID,CompanyID,DepartmentID,poshShopId,(sum(isnull(Quantity,0))/12)Qty from vwSalesAnalysisByItem v         
inner join ashops on poshShopId=ShopID and CompanyID= @CompanyID and (DepartmentID= @DepartmentID or @DepartmentID=0)        
where poshBillDate>= @startdate and poshBillDate<= @enddate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,',')) or @strCategoryID='') --and posdItemID=@strItemID         
group by posdItemID,poshShopId,DepartmentID,CompanyID          
        
---Lst24monthsAvg----        
set @startdate= dateadd(m,-24,@dtDate)        
set @enddate= dateadd(m,-1,@dtDate)        
set @startdate= dbo.ufn_GetFirstDayOfMonth(@startdate)        
set @enddate= dbo.ufn_GetLastDayOfMonth(@enddate)        
insert into #ItemDetail(ItemID,CompanyID,DepartmentID,SHOPID,Last24MonthAvg)          
select posdItemID,CompanyID,DepartmentID,poshShopId,(sum(isnull(Quantity,0))/24)Qty from vwSalesAnalysisByItem v         
inner join ashops on poshShopId=ShopID and CompanyID= @CompanyID and (DepartmentID= @DepartmentID or @DepartmentID=0)        
where poshBillDate>= @startdate and poshBillDate<= @enddate AND (ItemCategoryId IN (select * from fnsplit(@strCategoryID,',')) or @strCategoryID='') --and posdItemID=@strItemID         
group by posdItemID,poshShopId,DepartmentID,CompanyID          
        
exec(          
'SELECT '+ @STR1+@STR +  ' FROM #ItemDetail GROUP BY Itemid,StockDate,PreviousMonth )vw where itemid is not null Group by vw.Itemid)v         
inner join aitem a on v.ItemID=a.ItemID inner join aitemcategory c on c.ItemCategoryID=a.ItemCategoryID inner join adistributormaster d on d.did=a.did')          
 SET NOCOUNT OFF         
end          
          
----------------------------------        
        
Go
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--Ticket/Task ID:M_129
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO
IF EXISTS( SELECT * FROM SYSOBJECTS WHERE XTYPE='P' AND NAME='spvendorarriveexdiff')
BEGIN
	DROP PROCEDURE spvendorarriveexdiff
END
GO                     
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------    
----                 
--Modified on  : 08/02/2004                
--Modified by   : Hariharan                 
--Comments  : modified the vendor selection                
--Verified by      : Hariharan                 
--Verified Date     : 03/05/2004 (verified From Client DB)    
----modified by      : jyothish    
--modified Date     : 15/12/2011      
/*    
This SP modified and send to SIMDI as emergency. So to keep a back up I changed name of SP and placed in same server.    
    
*/     
/*
Ref No : 01
Modified	on : 18-04-2012
Modifed		By : Shine Das
Comments	   : Department wise TB was not tallying when adjustment done. 
Corrected it. (For consolidation option only)
*/   
CREATE proc spvendorarriveexdiff                     
 @intcompanyid as int, @strexrates as varchar(250),                     
 @strcurdate as varchar(10),@intDepartmentID as int=0, @DepWise as char(1) = 'd' as                    
begin                    
set nocount on                    
declare @intcount as int,                    
 @intvendorid as int,                    
 @numdepbal as numeric(18,2),                    
 @numconsbal as numeric(18,2),                    
 @numresbal as numeric(18,2),                    
 @strvendorname as varchar(250),                    
 @intDepCurrID as int,                    
 @intvenCurrID as int,                    
 @intConsCurrID as int,                    
 @numdepamount as numeric(18,2),                    
 @numConsamount as numeric(18,2),                    
 @straccounttype as char(1),                    
 @bitjournalcredit as bit,                    
 --@numdiffamt as numeric(18,2),                   
 @numdiffamtDep as numeric(18,2),                 
 @numdiffamtCon as numeric(18,2),                 
 @numEquiAmnt as numeric(18,2),
 
   @numResBalInConsCurrency as numeric(18,2)    --Ref No : 01                  
                  
                    
CREATE table #temp1(                    
 companyid int,                    
 vendorid int,                    
 vendorname varchar(250),                    
 CurrencyID int                    
 )                    
                    
CREATE table #temp2(                    
 companyid int,                    
 vendorid int,                    
 vendorname varchar(250),                    
 DepBalance numeric(18,2),                    
 consbalance numeric(18,2),                    
 resbalance numeric(18,2),                    
 depamount  numeric(18,2),                    
 consamount  numeric(18,2),                    
 journalcredit bit                    
 )                    
                    
select @intDepCurrID =depcurrencyid from aDepartmentMaster                     
 where companyid =@intcompanyid and departmentID= @intDepartmentID                    
select @intConsCurrID = currencyID from aCompanyMaster where companyId =@intCompanyID                    
-- all the vendor other than company currency are taken into the temp table                    
                  
if @DepWise ='d'                    
Begin                    
  insert into #temp1        
  select v.companyid, v.vendorid, vendorname,currencyid from avendormaster v, vwsupplierledger led         
where v.VendorID=led.VendorId and DepartmentId=@intDepartmentid and v.companyid =@intcompanyid                    
  --select distinct v.companyid, v.vendorid, vendorname,currencyid from avendormaster v left outer join                     
  --ASHOPVENDORDETAILS s on v.vendorid = s.vendorid and v.companyid =@intcompanyid and currencyid <> @intDepCurrID                    
  --left outer join ashops sh on s.ShopID=sh.ShopID and sh.companyid =v.companyid                   
  --and sh.departmentid = @intDepartmentid          
  ---jyothish modifed querry  15/12/2011                 
End                    
Else                    
Begin                    
  insert into #temp1                    
  select distinct V.companyid, V.vendorid, vendorname,currencyid from avendormaster v left outer join                     
  ASHOPVENDORDETAILS s  on v.vendorid = s.vendorid and v.companyid =@intcompanyid and currencyid <> @intConsCurrID                    
  left outer join ashops sh on s.ShopID=sh.ShopID and sh.companyid =v.companyid                   
  and sh.departmentid = @intDepartmentid                    
End                    
                
                
                
                
select @intcount = count(*) from #temp1                
while @intcount <> 0                    
begin -- for while                    
 select @intvendorid = vendorid, @strvendorname = vendorname,                     
 @intvenCurrID=currencyid from #temp1                      
 set @numconsbal = 0.0                    
 set @numdepbal = 0.0                  
 set @numresbal = 0.0                   
 set @numEquiAmnt = 0.0               
 set @numdiffamtDep  = 0.0              
 set @numdiffamtCon  =0.0               
             
                     
 if @DepWise ='d'                    
 BEGIN                  
  select @numresbal = sum(billamt) - sum(pmtamt), @numdepbal = sum(dbillamt) - sum(dpmtamt),@numconsbal = sum(cbillamt) - sum(cpmtamt)                   
  from vwsupplierledger where companyid = @intcompanyid and vendorid = @intvendorid                     
  and departmentID=@intDepartmentID and tDate <= @strcurdate                    
 END                  
 else                    
 BEGIN                  
  select @numresbal = sum(billamt) - sum(pmtamt), @numconsbal = sum(cbillamt) - sum(cpmtamt),@numdepbal = sum(dbillamt) - sum(dpmtamt)                  
  from vwsupplierledger where companyid = @intcompanyid and vendorid = @intvendorid                     
 and departmentID=@intDepartmentID and tDate <= @strcurdate                    
 END                  
 ---------------------------------------------------------------                  
 if @DepWise ='d'                     
 BEGIN                  
  set @numEquiAmnt=@numdepbal                  
  exec spConvertequiamount @intvenCurrID, 'm', @intDepCurrID,                     
  'm', @strexrates , @numresbal, @numdepamount output,  'r'                     
 END                  
 else                    
 BEGIN                  
  set @numEquiAmnt=@numconsbal                  
  --Ref No : 01 Commented Below
  --exec spConvertequiamount @intvenCurrID, 'm', @intConsCurrID,                     
  --'m', @strexrates , @numresbal, @numdepamount output,  'r'  
  
  --Ref No : 01  Added Below
    exec spConvertequiamount @intvenCurrID, 'm', @intConsCurrID,                     
  'm', @strexrates , @numresbal, @numResBalInConsCurrency output,  'r'  
                     
 END                  
 ---------------------------------------------------------------                  
 --Ref No : 01 Commented Below
 /*
 --------if abs(@numEquiAmnt - @numdepamount) >= 1 -- this has the exchange difference                    
 --------BEGIN                    
 --------if (@numdepamount > @numEquiAmnt)                     
 --------BEGIN                  
 -------- set @bitjournalcredit =1                    
 --------END                  
 --------if (@numdepamount < @numEquiAmnt)                    
 --------BEGIN                   
 -------- set @bitjournalcredit =0                    
 --------END                  
 */ --Ref No : 01 End
  if abs(@numEquiAmnt - @numResBalInConsCurrency) >= 1 -- this has the exchange difference                    
 BEGIN                    
 if (@numResBalInConsCurrency > @numEquiAmnt)                     
 BEGIN                  
  set @bitjournalcredit =1                    
 END                  
 if (@numResBalInConsCurrency < @numEquiAmnt)                    
 BEGIN                   
  set @bitjournalcredit =0                    
 END           
 
 ------------------------                
  if @DepWise ='d'                  
  begin                
  set @numdiffamtDep  = abs(@numdepamount - @numEquiAmnt)                
  set @numdiffamtCon  = abs(@numdepamount - @numconsbal)                  
  end                  
  else                
  begin                
  set @numdiffamtDep  = abs(@numdepamount - @numdepbal)                
  --set @numdiffamtCon  = abs(@numdepamount - @numEquiAmnt)        --Ref No : 01 Commented
   set @numdiffamtCon  = abs(@numResBalInConsCurrency - @numconsbal)              
  end                
    -------------------------                
                  
  if @DepWise ='d'                     
  BEGIN                    
    ---exec spConvertequiamount @intDepCurrID, 'm', @intConsCurrID,                     
    ---'m', @strexrates , @numdiffamt, @numConsamount output,  'r'                     
    ---insert into #temp2 values (@intcompanyid, @intvendorid, @strvendorname, @numdepbal,                     
    ---@numConsbal,@numresbal,@numdepamount,@numConsamount , @bitjournalcredit)                    
                  
    insert into #temp2 values (@intcompanyid, @intvendorid, @strvendorname, @numdepbal,          
    @numConsbal,@numresbal,@numdiffamtDep,@numdiffamtCon, @bitjournalcredit)                    
  END                    
  else                    
  BEGIN                    
   --Ref No : 01 Commented Below
    ---exec spConvertequiamount @intConsCurrID, 'm', @intDepCurrID,                     
    ---'m', @strexrates , @numdiffamt, @numConsamount output,  'r'    
    
     --Ref No : 01 Added Below
    exec spConvertequiamount @intConsCurrID, 'm', @intDepCurrID,             
    'm', @strexrates , @numdiffamtCon, @numdiffamtDep output,  'r'  
                     
    ---insert into #temp2 values (@intcompanyid, @intvendorid, @strvendorname, @numdepbal,                     
    ---@numConsbal,@numresbal,@numConsamount ,@numdepamount, @bitjournalcredit)                   
                    
insert into #temp2 values (@intcompanyid, @intvendorid, @strvendorname, @numdepbal,                     
    @numConsbal,@numresbal,@numdiffamtDep,@numdiffamtCon , @bitjournalcredit)                    
  END                    
 END  ---END OF exchange difference                    
 delete from #temp1 where vendorid = @intvendorid                    
 select @intcount = count(*) from #temp1                    
end -- for while                    
select * from #temp2                    
set nocount off                    
end           
GO         
                    
                                        
Go
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
--Ticket/Task ID:M_111 and M_112
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
GO
use [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spULSaleInv]    Script Date: 04/21/2012 12:27:12 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULSaleInv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULSaleInv]
GO

use [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spULSaleInv]    Script Date: 04/21/2012 12:27:12 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--Modified on   : 29/03/2004                    
--Modified by  : Hariharan R                    
--Comments  : Other charges changes                    
--   : Added customs duty Posting option                    
--   : ReInitialised other charges variable                    
--   : @chrShopType='B' included in custom duty posting condition                     
--   : as in transaction level the custom duty figure is saved                       
------------------------------------------------------------------------------                    
--RefNo-2                        
-- Modified on      : 2-12-2010 , 24/09/2011,04/10/11,19/11/11,22/11/11 ,07/01/2012                   
-- Modified by      : Nidheesh P V   ,Jyothish              
-- Comments         : Added the part of GST          
--,Comments          : post group id added      
--commets            : tax amount set 0 RefNo-5       
------------------------------------------------------------------------------                       
--RefNo-3                        
--Modified on  : 25/01/2012                    
--Modified by  : Bijesh.B                   
--Ticket Id    : CYI-281165    
--Comments     : Null Handled  (Other charges is not tallying)                 
------------------------------------------------------------------------------       
--RefNo-4                        
--Modified on  : 19/04/2012                    
--Modified by  : MANUNADH. U  
--Comments     : Change the precision of numeric variables from 2 to 9 for the 
--				 Task No: M_111 and M_112 specified in the Magnolia Issue Tracking System
------------------------------------------------------------------------------        
                  
CREATE proc [dbo].[spULSaleInv]                    
 @intCompanyID as int,                     
 @intShopId as int                     
as                     
begin                    
  Declare @intSalesAccountID as int,@intCashAccountID as int,@intJournalId as int,@intJournalDetailId as int,                    
 @intFinancialID   as int,@intInvoiceId    as int,@intCustomerId    as int,@intDiscountAccountID   as int,                    
 @intOtherChargesAccountID  as int,@intDepartmentID   as int,@intComCurID    as int,@intinventoryaccid   as int,                    
 @intCostOfGoodsAccId   as int,@intPlTransAccId   as int,@intcomdeptid    as int,@intCurrencyId    as int,                     
 @intcomprofitaccid   as int,@intCustomsDutyID   as int,--R Harikrishnan for Customs Duty Posting                    
 @numtotalinvValue as NumEric(18,2),@numTotalDiscountValue as NumEric(18,2),@numTotalCostValue as NumEric(18,2),  
 @numTotalOCValue   as NumEric(18,2),@depsalesval    as NumEric(18,2),@depcostval    as NumEric(18,2),                    
 @numTransEr as NumEric(18,2),@numAccEr as NumEric(18,2),  
 @numAaccAmt as NumEric(18,9),--<<RefNo-4>>  
 @NumDepAmt as NumEric(18,2),@numCustomsDutyAmt   as NumEric(18,2),--R Harikrishnan for Customs Duty Posting                    
 @numSalesValue as NumEric(18,2),@depExRate as NumEric(28,8),@NumEr as NumEric(28,8),  
 @numProfitTrans as NumEric( 7,5),@strExRates    as varchar(250),@strinvoiceNo    as varchar(50),                    
 @strRemarks    as varchar(250),@chrCustomsDutyPaidType  as char(1),--R Harikrishnan for Customs Duty Posting                    
 @chrShopType   as char(1),--R Harikrishnan for Customs Duty Posting                    
 @dtinvoiceDate    as datetime,@dtutime    as datetime                    
                    
  --RefNo-2-added for gst--                  
  --<<RefNo-4>>--START  
 declare @IntCount as int,@TaxCurrId as int,@numTaxEr as numeric(18,9),@TaxAcntId as int,@TaxCatId as int,  
 @TaxAmount as numeric(18,9),@CTaxAmount as numeric(18,9),@DTaxAmount as numeric(18,9),  
 @TaxAccAmount as numeric(18,9),@CTotalTaxAmount as numeric(18,9),@DTotalTaxAmount as numeric(18,9),           
 @TotalTaxAmnt as numeric(18,9),@TotalAccTax as numeric(18,9),@IntServTaxAccnt as integer,  
 @IntServTaxAccntCurrID as integer,@numOCTaxAmount as numeric(18,9)              
-----------------------------                    
 declare  @Taxtable table (                  
 taxTransId int,         
 taxShopId int,                        
 taxAccntId int,                  
 taxAmount numeric(18,9),                  
 CtaxAmount numeric(18,9),                  
 DtaxAmount numeric(18,9)                  
 )     
  --<<RefNo-4>>---END             
  --RefNo-2-added for gst--                  
  SET NOCOUNT ON                  
  --RefNo-2---to insert tax cateid,tax A/C & tax amount in the table variable---                  
  insert into @Taxtable                   
 select ihInvoiceId,ihShopID,TaxAccountId,isnull(sum(idItemTaxAmount),0)as TaxAmount,                  
   sum(isnull(idItemTaxAmount,0)* ihexchangerate) as ComTaxAmount,  
   sum(isnull(idItemTaxAmount,0)* ihdepExRate) as DepTaxAmount                  
 FROM losinvoiceheader ih   
   inner join losinvoicedetail id on ih.ihInvoiceId = id.idInvoiceId and ih.ihShopID = id.idShopID                 
   inner join ataxcategorymaster tc on TaxCompanyId=ih.ihCompanyId and idItemTaxCategory=TaxId                  
  and TaxCancelled=0 and TaxAccountable=1                    
 WHERE ihcancelled =0 and ihposted =0 and ihproforma = 0 AND ihcashinvoice =0 and ihtype ='i'                     
   and isnull(idItemTaxCategory,0)<>0 and isnull(TaxPercentage,0)<>0 and ih.ihCompanyId = @intCompanyID                         
   and ih.ihShopID = @intshopid                          
 group by  TaxAccountId,ihInvoiceId,ihShopID                    
  ---RefNo-2----                  
  /* getting the defaults into the variables */                    
  /* getting the maximum Journal ID FROM journal table */                    
  SELECT @intJournalId = isnull(max(JournalId),0) FROM moaJournalHeader WHERE CompanyID = @intCompanyID                    
  set @numTotalinvValue  = 0.0                    
  set @numTotalCostValue = 0.0                    
  set @numTotalDiscountValue = 0.0                    
  set @numTotalOCValue = 0.0                    
  set @numCustomsDutyAmt = 0.0 --R Harikrishnan for Customs Duty Posting                    
  select @intcomcurid = CurrencyId from acompanymaster where companyid = @intcompanyid                    
  --R Harikrishnan for Customs Duty Posting                    
  select @intDiscountAccountID = discountaccountid,@intOtherChargesAccountID = shopOtherChargesAccID,                    
 @numProfitTrans = isnull(RevisedCostPricePercent,0),@chrShopType = upper(left(futureVarchar,1))                    
  from ashops where ShopId = @intShopId                    
                    
  select @intCostOfGoodsAccId =CostofGoodsid, @intInventoryaccid =inventoryid,  
 @intPlTransAccId =profittransfercontrolacc, @intcomdeptid  =companydepartment,                     
 @intcomprofitaccid =compprofitshareacc                     
  from apackagesettings where companyid = @intcompanyid                    
  --To return if the corresponding accounts are not selected                    
  --R Harikrishnan 08/08/2003                    
  if isnull(@intCostOfGoodsAccId,0)=0 or isnull(@intInventoryaccid,0)=0                    
 return 0                    
  --To return if the corresponding accounts are not selected                    
  --R Harikrishnan 08/08/2003                    
  if @numProfitTrans>0 and (isnull(@intPlTransAccId,0)=0 or isnull(@intPlTransAccId,0)=0)                    
 return 0                    
    
  set @intJournalId = @intJournalId + 1                    
  --R Harikrishnan for Customs Duty Posting                    
  Declare invcur cursor for                     
 SELECT ihInvoiceId, ihinvoiceno, ihinvoicedate, ihCustomerId,ihremarks,ihdepartmentid,ihfinancialid,ihsalesaccid,   
   ihexchangerate, updatetime,ihdepExRate, ihexchangerates, ihCustomsDutyAccID, ihdutypaidby                    
 FROM losinvoiceheader                     
 WHERE ihcancelled =0 and ihposted =0 and ihproforma = 0 and ihCompanyID = @intCompanyID and ihShopId = @intShopId   
   and ihcashinvoice =0 and ihtype ='i'                     
                      
 open invcur                    
      --R Harikrishnan for Customs Duty Posting                    
   fetch next FROM invcur into                     
  @intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId, @strremarks,@intdepartmentid, @intfinancialid,   
  @intsalesaccountid, @NumEr, @dtutime,@depExRate, @strExRates, @intCustomsDutyID, @chrCustomsDutyPaidType                    
   while @@Fetch_status = 0                    
  begin                    
    set @numTotalinvValue  = 0.0                    
    set @numTotalCostValue = 0.0                    
    set @numTotalDiscountValue = 0.0                    
    set @numTotalOCValue = 0.0                    
    set @numCustomsDutyAmt = 0.0                     
          --FOR GETTING TRANS EXCHANGE RATE                    
    select @intCurrencyId = CurrencyId from aCustomerMaster where CustomerId = @intCustomerId                    
          exec spReturnExRate @intCurrencyId, @strExRates, @numTransEr output                    
          --R Harikrishnan for Customs Duty Posting                    
    --FOR GETTING TRANS EXCHANGE RATE                    
    SELECT @numTotalinvValue = sum(idactualunitprice),@numTotalDiscountValue = sum(idunitprice),                    
   @numCustomsDutyAmt = isnull(sum(isnull(idcdcustcur,0.00)),0.00),                    
   @numTotalCostValue = isnull(sum(idquantity * idcostprice),0)                    
    FROM losinvoicedetail WHERE idShopId = @intShopId and idInvoiceId  = @intInvoiceId                     
    group by idShopId, idInvoiceId                    
                    
    --R Harikrishnan for Customs Duty Posting                    
    --Checking whether the AccountID is saved in the transaction                    
    if (@chrShopType='B' and @chrCustomsDutyPaidType<>'C' and isnull(@intCustomsDutyID,0) = 0   
   AND @numCustomsDutyAmt>0)                    
   Begin                    
     Close invcur                    
     Deallocate invcur                    
     Return 0                    
   End                    
          -----------------------------------------------            
          SELECT @numTotalOCValue = sum(ioAmount),@numOCTaxAmount = sum(isnull(ioServTaxAmount,0)) --RefNo-3 Null handled                 
    FROM losInvoiceOC WHERE ioShopId = @intShopId and ioInvoiceId = @intInvoiceId group by ioShopId,ioInvoiceId                    
          --To return if the corresponding accounts are not selected                    
    --R Harikrishnan 08/08/2003                    
    if isnull(@intOtherChargesAccountID,0)=0 and @numTotalOCValue<>0                    
   begin                    
     Close invcur                    
     Deallocate invcur                    
     return 0       
   end         
          Set @numSalesValue = @numTotalDiscountValue                     
          --R Harikrishnan for Customs Duty Posting                    
    /*if (@chrShopType='B' and @chrCustomsDutyPaidType<>'C')                    
   begin     
     set @numTotalDiscountValue = @numTotalDiscountValue + @numTotalOCValue + @numCustomsDutyAmt                    
   end                    
    else                    
   begin       
     set @numTotalDiscountValue = @numTotalDiscountValue + @numTotalOCValue                     
     set @numCustomsDutyAmt = 0.00                    
      end */                    
          insert into moaJournalHeader(JournalId, CompanyID, JournalDate, referenceno, remarks, financialID,                     
   Type, CurrencyId, chequedate, updatetime)                     
    values (@intJournalId, @intCompanyID, @dtinvoicedate, @strinvoiceNo,                     
   @strRemarks, @intFinancialID,'SCI', @intcomCurID,@dtinvoicedate, @dtutime)                    
                    
    set @intJournalDetailId = 1         
    ---  RefNo-5             
    set @TotalTaxAmnt=0.00                  
    set @CTotalTaxAmount=0.00                  
    set @DTotalTaxAmount=0.00     
          --RefNo-2--------------------------------------                   
    select @TotalTaxAmnt=sum(isnull(taxAmount,0)),@CTotalTaxAmount=sum(isnull(CtaxAmount,0)),  
      @DTotalTaxAmount=sum(isnull(DtaxAmount,0))                   
    from @Taxtable where taxTransId=@intInvoiceId and taxShopId=@intShopId group by taxTransId,taxShopId                  
                  
    if @TotalTaxAmnt is null                   
   begin                  
     set @TotalTaxAmnt=0.00                  
     set @CTotalTaxAmount=0.00                  
     set @DTotalTaxAmount=0.00                  
   end                  
    --TO CONVERT INTO SALE A/C CURRENCY---                  
    select @intCurrencyId = CurrencyId from  aAccountMaster  where accountid = @intSalesAccountID                    
          exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                     
    exec spconvertcurrency @numTransEr , @numAccEr , @TotalTaxAmnt,@TotalAccTax output                    
    --TO CONVERT INTO SALE A/C CURRENCY---                  
    --RefNo-2----------------------------------------                  
                      
    --FOR CONVERTING AMOUNT--->                    
    select @intCurrencyId = CurrencyId from  aAccountMaster  where accountid = @intSalesAccountID                    
          exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                     
          exec spConvertCurrency @numTransEr , @numAccEr, @numSalesValue ,@numAaccAmt output                    
          --FOR CONVERTING AMOUNT <---                    
          /* crediing the sales account with the full invoice Amount */                    
    insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                     
   Amount, actualAmount, departmentID, depamount, PostGroup)                    
    values (@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intSalesAccountID,   
   (@numSalesValue * @NumEr)-(@CTotalTaxAmount),(@numAaccAmt-@TotalAccTax),@intDepartmentID,   
   (@numSalesValue * @depExRate)-(@DTotalTaxAmount), 1)  --RefNo-2---tax amount is deducted                    
                  
          set @intJournalDetailId = @intJournalDetailId +1                    
          if @numTotalOCValue >0                     
   begin        
              -- DEBITING customer with other charges                    
     insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerId,                     
    Amount, actualAmount, departmentID, depamount, PostGroup)             
     values(@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intCustomerId,                     
    @numTotalOCValue * @NumEr, @numTotalOCValue,@intDepartmentID, @numTotalOCValue * @depExRate, 2)                    
                     
     set @intJournalDetailId = @intJournalDetailId + 1              
              set @numTotalOCValue=@numTotalOCValue-@numOCTaxAmount    -------            
     select @intCurrencyId = CurrencyId from aAccountMaster where accountid = @intOtherChargesAccountID                    
              exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                     
              exec spConvertCurrency @numTransEr , @numAccEr , @numTotalOCValue,@numAaccAmt output                    
     --FOR CONVERTING AMOUNT <---                    
                    
     /* crediing the sales account with the full invoice Amount */                    
     insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                     
    Amount, actualAmount, departmentID, depamount, PostGroup)                    
     values(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intOtherChargesAccountID,   
    @numTotalOCValue* @NumEr,@numAaccAmt, @intDepartmentID, @numTotalOCValue * @depExRate, 2)           
     set @intJournalDetailId = @intJournalDetailId + 1               
              -----------------------------------------------------------------------------------------------------            
     /* crediing the other charge amount to service tax account  */                    
     select @IntServTaxAccnt=t.TaxAccountId ,@IntServTaxAccntCurrID=a.CurrencyID            
     from ashops s inner join aTaxCategoryMaster t on s.ServiceTaxCategoryId=t.TaxId             
    inner join aAccountMaster a on a.AccountID=t.TaxAccountId            
                  
              exec spReturnExRate @IntServTaxAccntCurrID, @strExRates, @numAccEr output                     
     exec spConvertCurrency @numTransEr , @numAccEr , @numOCTaxAmount,@numAaccAmt output                    
     --FOR CONVERTING AMOUNT <---                 
              insert into moaJournalDetails(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                     
    Amount, actualAmount, departmentID, depamount, PostGroup)                    
     values(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@IntServTaxAccnt,@numOCTaxAmount* @NumEr,  
    @numAaccAmt, @intDepartmentID, @numOCTaxAmount * @depExRate, 2)                    
              set @intJournalDetailId = @intJournalDetailId + 1                    
     --------------------------------------------------------------------------------------------------------            
            end                     
          --R Harikrishnan for Customs Duty Posting                    
    if @numCustomsDutyAmt >0 and @chrCustomsDutyPaidType<>'C' and @chrShopType='B'                     
   Begin                    
     select @intCurrencyId = CurrencyId from aAccountMaster where accountid = @intCustomsDutyID                    
     exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                    
              exec spConvertCurrency @numTransEr , @numAccEr,@numCustomsDutyAmt, @numAaccAmt output                    
     -- crediing the Customs Duty account                     
     insert into moaJournalDetails(JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                     
    Amount, actualAmount, departmentID, depamount, PostGroup)                    
        values(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intCustomsDutyID,   
    @numCustomsDutyAmt * @NumEr,@numAaccAmt, @intDepartmentID,@numCustomsDutyAmt * @depExRate, 3)                    
     set @intJournalDetailId = @intJournalDetailId + 1                    
                    
     -- DEBITING customer Custom Duty amount                    
     insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerId,                     
    Amount, actualAmount, departmentID, depamount, PostGroup)                    
     values(@intJournalId, @intJournalDetailId,@intCompanyID,0,@intCustomerId,@numCustomsDutyAmt * @NumEr,   
    @numCustomsDutyAmt,@intDepartmentID, @numCustomsDutyAmt * @depExRate, 3)                    
              set @intJournalDetailId = @intJournalDetailId + 1                     
   End                    
          -- DEBITING customer Invoice amount                    
    insert into moaJournalDetails(JournalId, JournalDetailId, CompanyID, JournalCrEDit, CustomerId,                     
   Amount, actualAmount, departmentID, depamount, PostGroup)                    
    values(@intJournalId, @intJournalDetailId, @intCompanyID,0,@intCustomerId,@numTotalDiscountValue * @NumEr,   
   @numTotalDiscountValue,@intDepartmentID, @numTotalDiscountValue * @depExRate, 1)                    
          set @intJournalDetailId = @intJournalDetailId + 1                     
          -- FOR CONVERTING AMOUNT --->                    
    select @intCurrencyId = CurrencyId from aAccountMaster where accountid = @intINVentoryAccID                    
    exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                     
          exec spConvertCurrency @numTransEr, @numAccEr, @numTotalCostValue,@numAaccAmt output                    
    if @numTotalCostValue<>0                  
      begin                    
     --FOR CONVERTING AMOUNT <---                    
              /* crediing the INVENTORY with the full cost Amount */                    
     insert into moaJournalDetails(JournalId, JournalDetailId, CompanyID,JournalCrEDit, AccountID, Amount,   
    actualAmount, departmentID, depamount, PostGroup)                    
     values (@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intINVentoryAccID,   
    @numTotalCostValue * @NumEr, @numAaccAmt,@intDepartmentID, @numTotalCostValue * @DepExRate , 4)                             
     set @intJournalDetailId = @intJournalDetailId +1                    
              --FOR CONVERTING AMOUNT--->                    
     select @intCurrencyId = CurrencyId from aAccountMaster where accountid = @intCostOfGoodsAccId                      
              exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                     
              exec spConvertCurrency @numTransEr, @numAccEr, @numTotalCostValue,@numAaccAmt output                    
     --FOR CONVERTING AMOUNT <---                    
              -- DEBITING THE COST OF GOODS ACCOUNT                    
     insert into moaJournalDetails(JournalId, JournalDetailId,CompanyID,JournalCrEDit, AccountID, Amount,   
    actualAmount,departmentID, depamount, PostGroup)                    
     values(@intJournalId, @intJournalDetailId, @intCompanyID, 0,@intCostOfGoodsAccId,   
    @numTotalCostValue * @NumEr, @numAaccAmt,@intDepartmentID, @numTotalCostValue * @depExRate, 4)                    
   end                    
    -- transfering the profit to company department                    
    -- calcuating the shopwise profit transfering based on RevisedCostPricePercent                    
          --RefNo-2-----------------------------------                  
    select @IntCount=count(*) from @Taxtable where taxTransId=@intInvoiceId and taxShopId=@intShopId                 
    while (@IntCount>0)                  
    begin                  
   select top 1 @TaxAcntId=taxAccntId,@CTaxAmount=CtaxAmount,@TaxAmount=taxAmount,@DTaxAmount=DtaxAmount                   
   from @Taxtable where taxTransId=@intInvoiceId and taxShopId=@intShopId order by taxAccntId                  
                  
   --TO GET TAX EXCHANGE RATE --------------->                        
   select @TaxCurrId = currencyid from aaccountmaster a where accountid = @TaxAcntId                        
   exec spReturnExrate @TaxCurrId, @strExRates, @numTaxEr output                        
   --TO GET TAX EXCHANGE RATE <---------------                        
   ---------------------------------------                        
   exec spconvertcurrency @numTransEr , @numTaxEr , @TaxAmount,@TaxAccAmount output                    
   ------------------------------------------                  
   set @intjournalDetailID=@intjournalDetailID+1                  
   /* crediting TO TAX ACCOUNT   */                  
   insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                     
    Amount, actualAmount, departmentID, depamount, PostGroup)                    
   values(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@TaxAcntId, @CTaxAmount,                     
   @TaxAccAmount,@intDepartmentID, @DTaxAmount, 1)                    
                   
   delete from @Taxtable where taxTransId=@intInvoiceId and taxShopId=@intShopId and taxAccntId=@TaxAcntId                 
   set @IntCount=@IntCount-1                  
    end                  
    --RefNo-2-------------------------------------------                  
                  
    if @numProfitTrans <> 0                    
   begin                    
     -- FOR CONVERTING TO ACCOUNT AMOUNT---------->                    
              select @intCurrencyId = CurrencyId from aAccountMaster where accountid = @intPlTransAccId                    
              exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                  
              exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,@numAaccAmt output                  
              select @intCurrencyId = depCurrencyId from adepartmentmaster where departmentid = @intcomdeptid                    
              exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                     
              exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,@NumDepAmt output                    
                    
     -- FOR CONVERTING TO ACCOUNT AMOUNT<------------------                    
     set @intJournalDetailId = @intJournalDetailId + 1                     
              -- credit transfer control account with shop department                    
     insert into moaJournalDetails(JournalId, JournalDetailId, CompanyID,JournalCrEDit, AccountID, Amount,   
    actualAmount,departmentID, depamount, PostGroup)                    
     values (@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intPlTransAccId ,   
    @numTotalCostValue * @NumEr * @numProfitTrans * 0.01,@numAaccAmt * @numProfitTrans * 0.01,   
    @intDepartmentID,@numTotalCostValue * @numProfitTrans * 0.01 * @depExRate, null )                    
              set @intJournalDetailId = @intJournalDetailId +1                     
                       
     -- credit transfer control account with comp department                    
     insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID,JournalCrEDit, AccountID, Amount,   
    actualAmount,departmentID, depamount, PostGroup)                    
     values (@intJournalId, @intJournalDetailId, @intCompanyID, 0,@intPlTransAccId ,   
    @numTotalCostValue * @NumEr * @numProfitTrans * 0.01,@numAaccAmt * @numProfitTrans * 0.01,   
    @intcomdeptid,@numDepAmt * @numProfitTrans * 0.01, null)                    
              -- FOR CONVERTING TO ACCOUNT AMOUNT ---------->                    
     select @intCurrencyId = CurrencyId from aAccountMaster where accountid = @intcomprofitaccid                    
              exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                     
              exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,@numAaccAmt output                    
              select @intCurrencyId = depCurrencyId from adepartmentmaster where departmentid = @intcomdeptid                    
                      
     exec spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                     
              exec spConvertCurrency @numTransEr , @numAccEr , @numTotalCostValue,@NumDepAmt output                    
     -- FOR CONVERTING TO ACCOUNT AMOUNT< ----------       
              set @intJournalDetailId = @intJournalDetailId +1                    
              insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID,JournalCrEDit, AccountID, Amount,   
    actualAmount,departmentID, depamount, PostGroup)                    
     values(@intJournalId, @intJournalDetailId, @intCompanyID, 1,@intcomprofitaccid ,   
    @numTotalCostValue * @NumEr * @numProfitTrans * 0.01,@numAaccAmt * @numProfitTrans * 0.01,   
    @intcomdeptid,@numDepAmt * @numProfitTrans * 0.01, null )                    
                    
     -- debit company profit account with shop department                     
     set @intJournalDetailId = @intJournalDetailId +1                    
              insert into moaJournalDetails (JournalId, JournalDetailId, CompanyID,JournalCrEDit, AccountID, Amount,   
    actualAmount,departmentID, depamount, PostGroup)                    
     values(@intJournalId, @intJournalDetailId, @intCompanyID, 0,@intcomprofitaccid ,   
    @numTotalCostValue * @NumEr * @numProfitTrans * 0.01,@numAaccAmt * @numProfitTrans * 0.01,   
    @intDepartmentID,@numTotalCostValue * @numProfitTrans * 0.01 * @depExRate, null )                     
   end                    
          /* mark the record as postED */                    
    update losinvoiceheader set ihpostED =1 WHERE ihCompanyID = @intCompanyID                     
   and ihShopId = @intShopId and ihInvoiceId = @intInvoiceId                     
                    
    set @intJournalId = @intJournalId + 1                    
          --R Harikrishnan for Customs Duty Posting                    
    fetch next FROM invcur into @intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId,@strremarks,   
   @intdepartmentid, @intfinancialid, @intsalesaccountid,@NumEr, @dtutime,@depExRate, @strExRates,   
   @intCustomsDutyID,@chrCustomsDutyPaidType                     
  end                    
   Close invcur                    
   Deallocate invcur                    
 SET NOCOUNT OFF                  
end  
GO


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_175
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
use [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spUpdateLedgersServiceInv]    Script Date: 11/04/2011 16:38:06 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUpdateLedgersServiceInv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spUpdateLedgersServiceInv]
GO

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spUpdateLedgersServiceInv]    Script Date: 11/04/2011 16:38:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

 /****** Object:  Stored Procedure dbo.spUpdateLedgersServiceInv    Script Date: 18/01/2003 9:45:45 PM      
-- Last Modified on : 01/12/2002      
-- Modifed by       : leo    
  
Ref No1  
Modified By: Shine Das  
Modified On: 22.09.2011  
Comments   : Need to include Posting of GST  
 ------------------   
Ref No2  
Modified By: Nidheesh P V 
Modified On: 29.10.2011  
Comments   : Checked isnull condition    
  ------------------     
Ref No 3
Modified By: SHINE DAS
Modified On: 25.04.2012  
Comments   : Department amount for customer was wrong.
  ------------------      
*/    
CREATE proc [dbo].[spUpdateLedgersServiceInv] @intCompanyID as int, @intinvoiceid as int as         
begin        
Declare @intCashAccountID as int,        
 @intJournalID as int,        
 @intJournalDetailID as int,        
 @intSAccountID as int,        
 @numSAmount as numeric(18,2),        
 @intFinancialID as int,        
 @dtInvoiceDate as datetime,        
 @intCustomerID as int,        
 @strInvoiceNo as varchar(50),        
 @strRemarks as varchar(200),        
 @intDiscountAccountID as int,        
 @numDiscount as numeric(18,2),        
 @intDepartmentID as int,        
 @bitCash as bit,        
 @bitProduct as bit,        
 @numTotalInvValue as numeric(18,2),        
 @dtutime as datetime,        
 @numconsrate as numeric(18,9),        
 @numdeprate as numeric(18,9),        
 @intcurrencyid as int,        
 @strexrates as varchar(250),        
 @numseraccamt as numeric(18,2),      
 @intServiceTaxID INT, ---Ref No1      
 @intGSTOutPutAccountID INT, ---Ref No1      
 @numGSTTaxAmount as numeric(18,9), ---Ref No1       
 @numAccGSTTaxAmount as numeric(18,9) ---Ref No1     
        
        
 /* getting the maximum Journal ID FROM journal table */        
 SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader WHERE         
 CompanyID = @intCompanyID        
       
  ---Ref No1  start      
 select @intServiceTaxID=isnull(TaxCategoryforServices,0) from apackagesettings      
 IF (@intServiceTaxID<>0)      
 Begin      
  select @intGSTOutPutAccountID=TaxAccountId from aTaxCategoryMaster where TaxId  =@intServiceTaxID        
 END      
--- ---Ref No1  end    
          
 set @intJournalID = @intJournalID + 1        
         
 ---Ref No1  Commented below snippet       
 /*    
 SELECT @intInvoiceID= InvoiceID, @dtInvoiceDate = InvoiceDate, @intCustomerID =         
 CustomerID, @strInvoiceno = InvoiceNo, @strRemarks = case when (chequeno is null or         
 chequeno ='') then remarks else chequeno + ';' + remarks end, @intDiscountAccountID =        
 DiscountAccountID, @numDiscount = Discount, @intDepartmentID = DepartmentID,         
 @bitProduct = Product, @intFinancialID = FinancialID, @intCashAccountID = BankCashID,         
 @numconsRate = exchangeRate, @dtutime = updatetime, @numdeprate = depexrate,         
 @strexrates = exchangerates FROM AccountsInvoiceHeader         
 WHERE Cancelled = 0 and Posted = 0 and CompanyID = @intCompanyID and Proforma = 0 and         
 Product = 0 and invoiceid = @intInvoiceID        
 */    
  SELECT @intInvoiceID= InvoiceID, @dtInvoiceDate = InvoiceDate, @intCustomerID =         
 CustomerID, @strInvoiceno = InvoiceNo, @strRemarks = case when (chequeno is null or         
 chequeno ='') then remarks else chequeno + ';' + remarks end, @intDiscountAccountID =        
 DiscountAccountID, @numDiscount = isnull(Discount,0) , @intDepartmentID = DepartmentID,   -- Ref No2     
 @bitProduct = Product, @intFinancialID = FinancialID, @intCashAccountID = BankCashID,         
 @numconsRate = exchangeRate, @dtutime = updatetime, @numdeprate = depexrate,         
 @strexrates = exchangerates, @numGSTTaxAmount=isnull(TaxAmount,0) FROM AccountsInvoiceHeader  --Ref No2       
 WHERE Cancelled = 0 and Posted = 0 and CompanyID = @intCompanyID and Proforma = 0 and         
 Product = 0 and invoiceid = @intInvoiceID        
        
 set @numTotalInvValue =0        
     
      exec spConvertequiamount @intcustomerid, 'c', @intGSTOutPutAccountID, 'a',         
  @strexrates, @numGSTTaxAmount, @numAccGSTTaxAmount output       
             
 -- get cash or crEDit        
 if (@intCashAccountID is null) --crEDit trans        
 begin          
  SELECT @intcurrencyid = CurrencyID FROM aCustomerMaster         
  WHERE CompanyID = @intCompanyID and CustomerID = @intCustomerID        
        
  INSERT INTO moajournalheader(JournalID, CompanyID, JournalDate, ReferenceNo,        
  Remarks, FinancialID, Type, CurrencyID, chequedate, updatetime)         
  VALUES (@intJournalID, @intCompanyID, @dtInvoiceDate, @strInvoiceNo,         
  @strRemarks, @intFinancialID, 'AI', @intcurrencyid, @dtinvoicedate, @dtutime)        
        
  set @intJournalDetailID = 1        
        
  Declare ServiceInv cursor for        
  SELECT ServiceQty * Amount, AccountID FROM ServiceInvoiceDetails        
  WHERE CompanyID = @intCompanyID and InvoiceID = @intInvoiceID        
  ORDER BY InvoiceDetailID        
        
  open ServiceInv        
  FETCH NEXT FROM ServiceInv INTO @numSAmount, @intSAccountID        
        
  while @@fetch_status = 0        
  begin        
        
   exec spConvertequiamount @intcustomerid, 'c', @intSAccountID, 'a',         
   @strexrates, @numSAmount, @numseraccamt output         
        
   /* inserting the sales account with the full invoice Amount */        
   INSERT INTO moajournaldetails (JournalID, JournalDetailID, CompanyID,         
   JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)         
   VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 1,         
   @intSAccountID, (@numSAmount * @numconsRate),         
   @numseraccamt, @intDepartmentID, (@numSAmount * @numdepRate) )        
        
   set @numTotalInvValue  = @numTotalInvValue  + @numSAmount        
   set @intJournalDetailID = @intJournalDetailID +1        
   FETCH NEXT FROM ServiceInv INTO @numSAmount, @intSAccountID        
  end        
  close ServiceInv        
  deallocate ServiceInv        
        
       
  /* check if discount allowED if allowED then post discount details */        
  if @numDiscount > 0         
  begin        
   exec spConvertequiamount @intcustomerid, 'c', @intDiscountAccountID, 'a',         
   @strexrates, @numDiscount, @numseraccamt output         
        
   INSERT INTO moajournaldetails(JournalID, journaldetailID, CompanyID,        
   JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)         
   VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,         
   @intDiscountAccountID, (@numDiscount * @numconsRate),         
        
   @numseraccamt,@intDepartmentID, (@numDiscount * @numdepRate))        
        
   set @intJournalDetailID = @intJournalDetailID +1           
  end        
           
  INSERT INTO moajournaldetails (JournalID, JournalDetailID, CompanyID,         
  JournalCredit, CustomerID, Amount, ActualAmount,departmentID, depamount)         
  VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,         
  @intCustomerID, (((@numTotalInvValue-@numDiscount)+@numGSTTaxAmount)*@numconsRate),        
  (@numTotalInvValue - @numDiscount)+@numGSTTaxAmount,@intDepartmentID,         
  --((@numTotalInvValue-@numDiscount)+@numGSTTaxAmount*@numdepRate))        -----Ref No 3 IMPROPER BRACKETING FOUND
   ((@numTotalInvValue-@numDiscount)+@numGSTTaxAmount)*@numdepRate)
        
  set @intJournalDetailID = @intJournalDetailID +1       
        
 end  -- end for crEDit trans        
 else        
 begin -- cash trans        
  SELECT @intcurrencyid = CurrencyID FROM aaccountmaster         
  WHERE CompanyID = @intCompanyID and AccountID = @intCashAccountID        
        
  INSERT INTO moajournalheader(JournalID, CompanyID, JournalDate, ReferenceNo,        
  Remarks, FinancialID, Type, CurrencyID, chequedate,updatetime)         
  VALUES (@intJournalID, @intCompanyID, @dtInvoiceDate, @strInvoiceNo,         
  @strRemarks, @intFinancialID, 'AI', @intcurrencyid, @dtinvoicedate, @dtutime)        
        
  set @intJournalDetailID = 1        
        
  Declare ServiceInv cursor for        
  SELECT ServiceQty * Amount, AccountID FROM ServiceInvoiceDetails        
  WHERE CompanyID = @intCompanyID and InvoiceID = @intInvoiceID        
  ORDER BY InvoiceDetailID        
        
  open ServiceInv        
  FETCH NEXT FROM ServiceInv INTO @numSAmount, @intSAccountID        
        
  while @@fetch_status = 0        
  begin        
   exec spConvertequiamount @intCashAccountID, 'a', @intSAccountID, 'a',         
   @strexrates, @numSAmount, @numseraccamt output         
        
   /* inserting the sales account with the full invoice Amount */        
   INSERT INTO moajournaldetails (JournalID, JournalDetailID, CompanyID,         
   JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)         
   VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 1,         
   @intSAccountID, (@numSAmount * @numconsRate),         
   @numseraccamt, @intDepartmentID, (@numSAmount * @numdepRate))        
        
   set @numTotalInvValue  = @numTotalInvValue  + @numSAmount        
        
   set @intJournalDetailID = @intJournalDetailID +1        
   FETCH NEXT FROM ServiceInv INTO @numSAmount, @intSAccountID        
  end        
  close ServiceInv        
  deallocate ServiceInv        
        
  /* check if discount allowED if allowED then post discount details */        
  if @numDiscount > 0         
  begin        
   exec spConvertequiamount @intCashAccountID, 'a', @intDiscountAccountID, 'a',         
   @strexrates, @numDiscount, @numseraccamt output         
        
   INSERT INTO moajournaldetails(JournalID, JournalDetailID, CompanyID,        
   JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)         
   VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 0,         
   @intDiscountAccountID, (@numDiscount * @numconsRate),         
   @numseraccamt, @intDepartmentID, (@numDiscount * @numdepRate))        
        
   set @intJournalDetailID = @intJournalDetailID +1           
  end        
        
  INSERT INTO moajournaldetails (JournalID, JournalDetailID, CompanyID,         
  JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)         
  VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 0,         
  @intCashAccountID, ((@numTotalInvValue - @numDiscount) *         
  @numconsRate),(@numTotalInvValue - @numDiscount),@intDepartmentID,         
  ((@numTotalInvValue - @numDiscount) * @numdepRate)  )        
  set @intJournalDetailID = @intJournalDetailID +1       
 end -- end for cash        
        
 /* mark the record as postED */        
 ---Ref No1 start posting of GST amount    
  IF (@intServiceTaxID<>0)      
 Begin      
  --   exec spConvertequiamount @intcustomerid, 'c', @intGSTOutPutAccountID, 'a',         
  --@strexrates, @numGSTTaxAmount, @numAccGSTTaxAmount output       
         
  INSERT INTO moajournaldetails (JournalID, JournalDetailID, CompanyID,         
  JournalCredit, AccountID, Amount, ActualAmount,departmentID, depamount)         
   VALUES (@intJournalID, @intJournalDetailID, @intCompanyID, 1,         
  @intGSTOutPutAccountID, (@numGSTTaxAmount * @numconsRate),         
  @numAccGSTTaxAmount, @intDepartmentID, (@numGSTTaxAmount * @numdepRate) )        
  set @intJournalDetailID = @intJournalDetailID +1           
 END      
 ---Ref No1 end posting of GST amount    
       
 UPDATE AccountsInvoiceHeader SET Posted = 1 WHERE CompanyID = @intCompanyID and         
 InvoiceID = @intInvoiceID         
        
end 
GO


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spULHPSaleInv]    Script Date: 11/04/2011 16:41:00 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spULHPSaleInv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spULHPSaleInv]
GO

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spULHPSaleInv]    Script Date: 11/04/2011 16:41:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


  
--Created on   : 27/11/2007                
--Created by  : Shinu                
--Comments  : For Posting HirePurchase Invoices         
--Modified by:Abhishek on 10/12/09        
--Comments:Take confirmed transactions for posting                  
---------------------------------------------------------------------           
--Modified By : Nidheesh PV       
--Modified Date : 01/10/2011,30/10/2011      
--Reference : RefNo:1   
--RefNo:1  is commented jyothish.SR Date:5-5-2012   
--Reason  Hp Customer balance is not tally in ledger
---------------------------------------------------------------------        
    
--spULHPSaleInv 1,4    
         
create  proc dbo.spULHPSaleInv                 
 @intCompanyID as int,                 
 @intShopId as int                 
as                 
                
begin                
 Declare @intJournalId    as int,                
  @intJournalDetailId   as int,                
  @intFinancialID   as int,                
  @intInvoiceId    as int,                
  @intCustomerId    as int,                  
  @intDepartmentID   as int,                
  @intComCurID    as int,                
  @intinventoryaccid   as int,                
  @intCostOfGoodsAccId   as int,                  
  @intcomdeptid    as int,                
  @intCurrencyId    as int,                 
  @intSalesaccid    as int,                 
  @intCustomerAccID   as int,                 
  @intSuspenseAccID  as int,                 
  @numtotalinvValue   as NumEric(18,2),                  
  @numTotalCostValue   as NumEric(18,2),                  
  @InterestAmount   as NumEric(18,2),                   
  @numSalesValue   as NumEric(18,2),            
  @numTotatInstAmount  as NumEric(18,2),                 
  @strinvoiceNo    as varchar(50),                
  @strRemarks    as varchar(250),                  
  @dtinvoiceDate    as datetime,                
  @dtutime    as datetime,                
  @numtaxamount as numeric(18,2), --RefNo:1-      
  @numSurcharge as numeric(18,2)  --RefNo:1-    
                
 /* getting the defaults into the variables */                
 /* getting the maximum Journal ID FROM journal table */                
 SELECT                 
  @intJournalId = isnull(max(JournalId),0)                 
 FROM                 
  moaJournalHeader                 
 WHERE                 
  CompanyID = @intCompanyID                
 --->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>                
 set @numTotalinvValue  = 0.0                
 set @numTotalCostValue = 0.0                 
 --->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>                
 select                 
  @intcomcurid = CurrencyId                 
 from                 
  acompanymaster                 
 where                 
  companyid = @intcompanyid                
 --->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>                
 select  @intcomdeptid  =companydepartment                 
                  
 from                 
  apackagesettings                 
 where                  
  companyid = @intcompanyid                
 --->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>                
 Select @intdepartmentid =DepartmentID From aShops where shopID=@intShopID                
 --->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>                
 Select                 
  @intCostOfGoodsAccId =COGSAcc, @intCustomerAccID =DebtorAcc,                 
  @intSalesaccid =SalesAcc,@intSuspenseAccID=SuspenseAcc                
 from                 
  ahpaccountssettings                 
 where                  
  companyid = @intcompanyid                
 --->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>                
 select  @intInventoryaccid =inventoryid                  
 from                 
  apackagesettings                 
 where                  
  companyid = @intcompanyid                
 --To return if the corresponding accounts are not selected                 
 if isnull(@intCostOfGoodsAccId,0)=0 or isnull(@intInventoryaccid,0)=0                
  return 0                
 --To return if the corresponding accounts are not selected                 
 if (isnull(@intCustomerAccID,0)=0 or isnull(@intSalesaccid,0)=0)                
  return 0                
 set @intJournalId = @intJournalId + 1                
                 
 Declare invcur cursor for                 
  SELECT                 
   hpqhQuotationID, hpqhQuotationNo, hpqhQuotationDate, hpqhCustomerId,  hpqhremarks,                 
   hpqhfinancialid,hpqhupdatetime,hpqhTotAdditional,hpqhInstPrice               
  FROM                 
   loshpinvoiceheader                 
  WHERE                 
   hpqhcancel =0 and hpqhposted =0  and hpqhConfirmed=1 and                
   hpqhCompanyID = @intCompanyID and hpqhShopId = @intShopId                
   and hpqhType='I'                   
 open invcur                
                 
 fetch next FROM invcur into                 
  @intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId, @strremarks,                 
  @intfinancialid,  @dtutime,@InterestAmount, @numTotatInstAmount               
 while @@Fetch_status = 0                
 begin                
  set @numTotalinvValue  = 0.0                
  set @numTotalCostValue = 0.0                   
  SELECT                 
   @numTotalinvValue = sum(hpqdCostPrice),                 
   @numTotalCostValue = sum(hpqdCostPrice),                
   @numSalesValue=sum(hpqdSellingPrice)                   
  FROM                 
   loshpinvoicedetail                 
  WHERE                 
   hpqdShopId = @intShopId and hpqdQuotationId  = @intInvoiceId                 
  group by                 
   hpqdShopId, hpqdQuotationId      
              
-------RefNo:1------      
--if exists (select * from losHpInvoiceDetailOthers where hpqdShopId = @intShopId and hpqdQuotationId  = @intInvoiceId)    
--begin  
  
  --select @numSalesValue=hpqdActSellingPrice      
  --,@InterestAmount=hpqdActInterest  
  --,@numSurcharge =hpqdActSurcharge      
  --,@numTotatInstAmount=hpqdActInstallmentPrice      
  --,@numtaxamount=hpqdTotalTax      
  --from losHpInvoiceDetailOthers      
  --WHERE hpqdShopId = @intShopId and hpqdQuotationId  = @intInvoiceId    
    
  --set @InterestAmount=@InterestAmount+@numSurcharge --Total Additional Amount->Interest A/C  
    
  --Actually Total Addition Amount is saved as Total Interest Amount and posted to Interest a/c.  
  --So interest amount is added upto Surcharge to find total Additional Amount           
---end     
-------RefNo:1------              
                
  insert into moaJournalHeader                 
   (JournalId, CompanyID, JournalDate, referenceno, remarks, financialID,                 
   Type, CurrencyId, chequedate, updatetime)                 
  values                 
   (@intJournalId, @intCompanyID, @dtinvoicedate, @strinvoiceNo,                 
   @strRemarks, @intFinancialID,'HPI', @intcomCurID,@dtinvoicedate, @dtutime)                
                
  set @intJournalDetailId = 1                 
                
  /* crediing the sales account with the full invoice Amount */                
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                 
   Amount, actualAmount, departmentID, depamount, PostGroup)                
  values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 1,                 
   @intSalesaccid, @numSalesValue,                 
   @numSalesValue,@intDepartmentID,@numSalesValue, 1)                
                
  set @intJournalDetailId = @intJournalDetailId +1                
  /* Crediting Interest Amount */                 
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountID,                 
   Amount, actualAmount, departmentID, depamount, PostGroup)                
  values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 1,                 
   @intSuspenseAccID, @InterestAmount,                 
   @InterestAmount,@intDepartmentID, @InterestAmount, 1)                
                
  set @intJournalDetailId = @intJournalDetailId +1                
  -- DEBITING customer Invoice amount          
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId, CompanyID, JournalCrEDit, AccountId,                 
   Amount, actualAmount, departmentID, depamount, PostGroup)                
   values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 0, @intCustomerAccID,                 
   @numTotatInstAmount, @numTotatInstAmount,                
   @intDepartmentID, @numTotatInstAmount, 1)                
                 
   set @intJournalDetailId = @intJournalDetailId + 1          
                
  /* crediing the INVENTORY with the full cost Amount */                
  insert into moaJournalDetails                 
   (JournalId, JournalDetailId, CompanyID,                 
   JournalCrEDit, AccountID, Amount, actualAmount, departmentID, depamount, PostGroup)                
  values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 1,                 
   @intINVentoryAccID, @numTotalCostValue, @numTotalCostValue,                
   @intDepartmentID,@numTotalCostValue , 4)                
                   
  set @intJournalDetailId = @intJournalDetailId +1                
                
  -- DEBITING THE COST OF GOODS ACCOUNT                
  insert into moaJournalDetails        
   (JournalId, JournalDetailId,CompanyID,                 
   JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount, PostGroup)                
  values                 
   (@intJournalId, @intJournalDetailId, @intCompanyID, 0,                 
   @intCostOfGoodsAccId, @numTotalCostValue, @numTotalCostValue,                 
   @intDepartmentID, @numTotalCostValue , 4)                
                
  /* mark the record as postED */                
  update loshpinvoiceheader set                 
   hpqhpostED =1                 
  WHERE                 
   hpqhCompanyID = @intCompanyID                 
   and hpqhShopId = @intShopId and hpqhQuotationId = @intInvoiceId                 
                
  set @intJournalId = @intJournalId + 1                
                  
  fetch next FROM invcur into                 
  @intInvoiceId, @strinvoiceno, @dtinvoicedate, @intCustomerId, @strremarks,                 
  @intfinancialid,  @dtutime,@InterestAmount,@numTotatInstAmount                
 end                
 Close invcur                
 Deallocate invcur                
                
end 
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_129
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
use adminv2;
go

if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'spUpdateLedgersAdjustments' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE spUpdateLedgersAdjustments
end
GO
/*  
       
 Last Modified : 07/02/2004      
 Modified by   : Hariharan R      
COMMENTS  : RESP AMOUNT posting done for` exchange diff acc      
Verified by      : Hariharan       
Verified Date     : 03/05/2004 (verified From Client DB)      
Modified By   :Benzigar S D    
Modified On   :20/03/2009    
Comment       :Modified Company and Department amount calculation for adjustment   
----------------------------------------------------------------------------------------------------
Ref No : 101
Modified By : SHINE DAS
Modified On : 05.05.2011
Comments	: Calcuation of amount which has to be posted to "Exchange Gain/Loss" account was wrong. 
-----------------------------------------------------------------
Ref No : 102
Modified By : SHINE DAS
Modified On : 24.02.2012
Comments	: To Correct Account wise Adjustment (client :SIMDI)

-----------------------------------------------------------------------------------------------------
Ref No : 103
Modified By : SHINE DAS
Modified On : 07.05.2012
Comments	: CALCULATION OF EXCHANGE GAIN OR LOSS WAS WRONG IN CONSOLIDATED WISE OPTION.
*/
-----------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------    
CREATE PROC spUpdateLedgersAdjustments @intCompanyID as int, @intAdjID as int as         
begin        
set nocount on        
Declare         
 @intjournalId as int,        
 @intAdjustmentDetailId as int,        
 @intRowCount as int,        
 @intCompanycurID as int,        
 @dtAdjustmentDate as datetime,        
 @strAdjustmentNo as varchar(50),        
 @strRemarks as varchar(250),        
 @numAmount as numeric(18,2),        
 @numExAmount as numeric(18,2),        
 @bitJC as bit,        
 @intAccountID as int,        
 @intcustomerid as int,        
 @intvendorid as int,        
 @numdAmount as numeric(18,2),        
 @numcAmount as numeric(18,2),        
 @strextype as char(1),        
 @intexaccountid as int,        
 @intfinancialid as int,        
 @intdepartmentid as int,         
 @adjType as varchar(2),         
 @intDepCurrID as int,         
 @strexrates as varchar(250),         
 @numDepExRate as numeric(18,8),        
 @numConExRate as numeric(18,8),     
 @numexamountDep  as numeric(18,8),    
 @numexamountCom  as numeric(18,8),       
 @numexamountAccnt  as numeric(18,8),  
  @numExGainorLoss as numeric(18,2),  ---Ref No : 101 New Variable Declared   
   @numAccAmount as numeric(18,2) ,
    @intAccCurrID as int   
      
 /* getting the maximum Journal ID FROM journal table */        
 SELECT @intjournalId = isnull(max(JournalID),0) FROM moaJournalHeader         
 WHERE CompanyID = @intCompanyID        
 SELECT @intCompanycurID = CurrencyID FROM acompanymaster         
 WHERE CompanyID =@intCompanyID        
         
 Declare JTcur cursor for         
 --SELECT AdjustmentID, AdjustmentNo, AdjustmentDate, remarks, amount, exchangegain,        
 --accountid, financialid, departmentid, AdjustmentType, Exchangerates,         
 --DepExchangerate, exchangeRate      
 --FROM AdjustmentHeader WHERE cancellED =0 and postED =0 and         
 --CompanyID = @intCompanyID and adjustmentid = @intAdjID     
 
  SELECT a.AdjustmentID, a.AdjustmentNo, a.AdjustmentDate, a.remarks, b.ConsAmount,b.ActualAmount,b.Amount , a.exchangegain,    
 a.accountid, a.financialid, a.departmentid, a.AdjustmentType, a.Exchangerates,     
 a.DepExchangerate, a.exchangeRate    
 FROM AdjustmentHeader a inner join AdjustmentDetails b on 
 a.AdjustmentID = b.AdjustmentID  
  WHERE a.cancellED =0 and a.postED =0 and     
 a.CompanyID = @intCompanyID and a.adjustmentid = @intAdjID
    
        
 open JTCur        
 fetch next FROM JTcur into @intAdjid, @strAdjustmentNo, @dtAdjustmentDate, @strremarks,    
 @numcAmount,@numAccAmount,@numdAmount, @strextype, @intexaccountid, @intfinancialid, @intdepartmentid, @adjType,     
 @strexrates, @numDepExRate, @numConExRate          
 while @@Fetch_status = 0        
 begin        
  Select @intDepCurrID = depCurrencyId from aDepartmentMaster where         
  departmentid = @intdepartmentid      
  
    Select @intAccCurrID = CurrencyID from aAccountMaster  where         
  AccountID = @intexaccountid     
  
   
    
  ---------------Ref No : 101 Start  
  if right(@ADJType, 1) ='D'         
   begin    
  -- select @numExGainorLoss = (select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID and JournalCredit =1) -   
  --(select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID  and JournalCredit =0)  
  select @numExGainorLoss =isnull((select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID  and JournalCredit =0),0)-  
  isnull((select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID and JournalCredit =1),0)  
    set @numexamountDep = @numexamount     
    set @numexamountCom = abs(@numExGainorLoss)  
    set @numexamountAccnt =(select sum(ActualAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)    
   end    
  else    
   begin    
   
  --- Ref No : 103  Added Below
       select @numexamountDep = abs(isnull((select sum(Amount) from AdjustmentDetails 
       where AdjustmentID=@intAdjID and CompanyID=@intCompanyID  and JournalCredit =0),0)-  
		isnull((select sum(Amount) from AdjustmentDetails 
		where AdjustmentID=@intAdjID and CompanyID=@intCompanyID and JournalCredit =1),0)) 

---Ref No : 103 Commented below
    -- select @numExGainorLoss = isnull((select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID  and JournalCredit =0),0)-  
    -- isnull((select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID and JournalCredit =1),0)  
    --set @numexamountDep = (select sum(amount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)    
    set @numexamountCom = 0.0  
    
 --- Ref No : 103 Added Below
  	exec spConvertequiamount @intDepCurrID, 'm', @intAccCurrID,       
	'm', @strexrates ,@numexamountDep, @numexamountAccnt output,  'r'   
 
 
    --set @numexamountAccnt = (select sum(ActualAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)    
   end    
  -----------Ref No : 101 End  
/*  
 ----------------------------------------   Ref No : 101 Commented Previous code - Start   
  if right(@ADJType, 1) ='D'         
  begin    
    
 set @numexamountDep = @numexamount     
 set @numexamountCom = (select sum(ConsAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)    
 set @numexamountAccnt =(select sum(ActualAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)    
  end    
  else    
  begin    
 set @numexamountDep = (select sum(amount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)    
 set @numexamountCom = @numexamount    
 set @numexamountAccnt = (select sum(ActualAmount) from AdjustmentDetails where AdjustmentID=@intAdjID and CompanyID=@intCompanyID)    
  end    
  ------------------------------------------  Ref No : 101 Commented Previous code - End  
  */    
  set @intjournalId = @intjournalId + 1        
  set @intAdjustmentDetailId = 1        
  insert into moaJournalHeader (JournalID, CompanyID, JournalDate, referenceno,         
  remarks, financialID,Type,CurrencyID,chequedate)   
  values (@intjournalid, @intCompanyID, @dtAdjustmentDate, @strAdjustmentNo,  @strRemarks,         
  @intFinancialID,'A',@intCompanycurID,@dtAdjustmentDate)        
        
  set @bitjc =0        
  -- accounting hte net         
  --if @strextype <> '' and @numexamount <> 0.0 
  
  if @strextype <> ''       
  begin        
  if upper(@strextype) ='I'        
   set @bitjc = 1        
  else        
   set @bitjc = 0        
        
  if right(@ADJType, 1) ='D'           
   exec spConvertequiamount @intDepartmentid, 'd',     
   @intexAccountID, 'a', @strexrates,     
   @numexAmount, @numAmount output,''    
  else    
   exec spConvertequiamount @intCompanycurID, 'm',      
   @intexAccountID, 'a', @strexrates,     
   @numexamountDep, @numAmount output,''         
         
        
  --insert into moajournaldetails (JournalID, journaldetailID, CompanyID,         
  --JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values        
  --( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,         
  --@intexAccountID, @numAmount * @numConExRate, @numAmount,         
  --@intDepartmentID, @numAmount * @numDepExRate)       
  ----@intexAccountID, @numexAmount * @numConExRate, @numAmount,         
  ----@intDepartmentID, @numexAmount * @numDepExRate)     
 ----------   insert into moajournaldetails (JournalID, journaldetailID, CompanyID,         
 ----------JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values        
 ----------( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,         
 ----------@intexAccountID, @numexamountCom, @numexamountAccnt,         
 ----------@intDepartmentID, @numexamountDep)    
 
 ---- Ref No : 103 Added
      insert into moajournaldetails (JournalID, journaldetailID, CompanyID,     
  JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values    
  ( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,     
  @intexAccountID, @numexamountCom * @numConExRate, @numexamountAccnt,     
  @intDepartmentID, @numexamountDep * @numDepExRate)  
     
   --- Ref No : 103 Commented
  --   insert into moajournaldetails (JournalID, journaldetailID, CompanyID,     
  --JournalCredit, AccountID, Amount, actualAmount,departmentid, Depamount) values    
  --( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,     
  --@intexAccountID, @numcAmount * @numConExRate, @numAccAmount,     
  --@intDepartmentID, @numdAmount * @numDepExRate)  
  
            
  set @intAdjustmentDetailId = @intAdjustmentDetailId + 1          
  end        
        
  Declare DetailCur cursor for        
  SELECT journalcrEDit, AccountID,customerid,vendorid, Amount, consamount,
	actualamount	------- Ref No : 01  added 
	FROM         
  adjustmentdetails WHERE CompanyID = @intCompanyID and adjustmentID = @intadjID        
         
  open DetailCur        
  fetch next FROM DetailCur into @bitJC, @intAccountID,         
  @intcustomerid, @intvendorid, @numdAmount, @numcAmount,
  @numAccAmount  ------- Ref No : 01  added        
  while @@Fetch_status =0        
  begin        
   if isnull(@intaccountid,0) <> 0         
   --insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,         
   --JournalCrEDit, AccountID, Amount, depamount, actualAmount,departmentid) values        
   --( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,         
   --@intAccountID, @numcAmount, @numdAmount,0.0,@intDepartmentID)   
	   --- Ref No : 01 Added Below
		   insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,     
   JournalCrEDit, AccountID, Amount, depamount, actualAmount,departmentid) values    
   ( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,     
   @intAccountID, @numcAmount, @numdAmount,@numAccAmount,@intDepartmentID)
        
   if isnull(@intcustomerid,0) <> 0     
   --- Ref No : 01 Commented Below
   ----insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,     
   ----JournalCrEDit, customerID, Amount, depamount, actualAmount,departmentid) values    
   ----( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,     
   ----@intcustomerID, @numcAmount, @numdAmount,0.0,@intDepartmentID)    
		   insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,     
   JournalCrEDit, customerID, Amount, depamount, actualAmount,departmentid) values    
   ( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,     
   @intcustomerID, @numcAmount, @numdAmount,@numAccAmount,@intDepartmentID) 
   
   if isnull(@intvendorid,0) <> 0     
   --- Ref No : 01 Commented Below
   ----insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,     
   ----JournalCrEDit, vendorID, Amount,depamount,  actualAmount,departmentid) values    
   ----( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,     
   ----@intvendorID, @numcAmount, @numdAmount,0.0,@intDepartmentID)    
		 insert into moaJournalDetails (JournalID, journaldetailID, CompanyID,     
   JournalCrEDit, vendorID, Amount,depamount,  actualAmount,departmentid) values    
   ( @intjournalId, @intAdjustmentDetailId, @intCompanyID, @bitJC,     
   @intvendorID, @numcAmount, @numdAmount,@numAccAmount,@intDepartmentID)    
   
    
   set @intAdjustmentDetailId = @intAdjustmentDetailId + 1    
   fetch next FROM DetailCur into @bitJC,     
   @intAccountID,  @intcustomerid, @intvendorid, @numdAmount, @numcAmount
   ,@numAccAmount  ----shine  added    
    
  end    
  Close DetailCur    
  Deallocate DetailCur    
      
        
  /* mark the record as postED */        
  update Adjustmentheader set postED =1 WHERE CompanyID = @intCompanyID and adjustmentID = @intadjID         
        
 fetch next FROM JTcur into @intAdjid, @strAdjustmentNo, @dtAdjustmentDate, @strremarks,    
 @numcAmount,@numAccAmount,@numdAmount, @strextype, @intexaccountid, @intfinancialid, @intdepartmentid, @adjType,     
 @strexrates, @numDepExRate, @numConExRate            
 end        
 Close JTCur        
 Deallocate JTCur        
set nocount off        
      
        
END
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_129
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
use adminv2;
go
if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'spaccountsarriveexdiff' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE spaccountsarriveexdiff
end
GO
-- Create by  : leo    
-- Last MOdified on : 14/04/2003, 17/11/2003    
-- Modified by  : leo, Hariharan R    
-- all the entries has to be posted to accounts before doing this procedure    
-- Included the code for removing the controll accounts    
--Modified to consider dep wise and company currrency wise and corrected     
-- difference amount picking  
--------------------------------------------------------------------------------------  
-- Modified By :-Benzigar S D  
-- Modified On :-28/07/2009  
-- Comment     :-Previously spopeningbalance is used to tale Opening Balance.  
--               Now spopeningbalance_Adjustment is used for this.  
--               In spopeningbalance journaldate-1 is taking.  
--               But here in adjustmentjournaldate is needed   
/*
Ref No		: 01
Modified By : SHINE DAS
Modified On : 23.02.2012
Client		: SIMDI
*/

/*
Ref No		: 02
Modified By : SHINE DAS
Modified On : 07.05.2012
Client		: SIMDI
Purpose		: Jomin reported that department wise TB is not tallying after this update.
So made corrections. 
*/
--------------------------------------------------------------------------------------  
CREATE proc spaccountsarriveexdiff @intcompanyid as int, @strexrates as varchar(250),           
 @strcurdate as varchar(10),@intDepartmentID as int, @Depwise char(1) ='d',           
@filtergroup as int = 0   as          
begin          
set nocount on          
declare @intcount as int,          
 @intaccid as int,          
 @numDepbal as numeric(18,2),          
 @numresbal as numeric(18,2),          
 @numconsbal as numeric(18,2),          
 @straccdesc as varchar(250),          
 @intDepCurrID as int,          
 @intAccCurrID as int,          
 @intConsCurrID as int,          
 @numdepamount as numeric(18,2),          
 @numConsamount as numeric(18,2),          
 @numresamountinConsCurr as numeric(18,2),   -- Ref No : 01    
 @straccounttype as char(1),          
 @bitjournalcredit as bit,          
 @numdiffamt as numeric(18,2)          
          
create table #temp1(          
 companyid int,          
 accountid int,          
 accountdesc varchar(250),          
 CurrencyID int,          
 type char(1)          
 )          
          
create table #temp2(          
 companyid int,          
 accountid int,          
 accountdesc varchar(250),          
 DepBalance numeric(18,2),          
 consbalance numeric(18,2),          
 resbalance numeric(18,2),          
 depamount  numeric(18,2),          
 consamount  numeric(18,2),      -- Ref No : 01    
 resamountinConsCurr  numeric(18,2), ---- Ref No : 01    
 journalcredit bit          
 )          
          
 select @intDepCurrID =depcurrencyid from aDepartmentMaster           
 where companyid =@intcompanyid and departmentID= @intDepartmentID          
 select @intConsCurrID = currencyID from aCompanyMaster where companyId =@intCompanyID          
-- all the account heads other than company currency are taken into the temp table          
          
if @Depwise ='d'          
Begin          
insert into #temp1          
select           
 a.companyid, a.accountid, a.accountdesc, a.Currencyid, g.accounttype from           
 aaccountmaster a, adeptaccounts d, agroupmaster g          
 where g.companyid = a.companyid and g.groupid = a.groupid and a.companyid =           
 d.dacompanyid and a.accountid = d.daaccountid and a.companyid           
 =@intcompanyid and a.currencyid <> @intDepCurrID  and d.dadepartmentid =           
 @intdepartmentid           
end          
else          
Begin          
insert into #temp1          
select           
    
    -- Ref No	: 02 Commented
 --a.companyid, a.accountid, a.accountdesc, a.Currencyid, g.accounttype from           
 --aaccountmaster a, adeptaccounts d, agroupmaster g          
 --where g.companyid = a.companyid and g.groupid = a.groupid and a.companyid =           
 --d.dacompanyid and a.accountid = d.daaccountid and a.companyid           
 --=@intcompanyid and a.currencyid <> @intConsCurrID  and d.dadepartmentid =           
 --@intdepartmentid  
     
     -- Ref No	: 02 Added
 a.companyid, a.accountid, a.accountdesc, a.Currencyid, g.accounttype from           
 aaccountmaster a, adeptaccounts d, agroupmaster g          
 where g.companyid = a.companyid and g.groupid = a.groupid and a.companyid =           
 d.dacompanyid and a.accountid = d.daaccountid and a.companyid           
 =@intcompanyid  and d.dadepartmentid = @intdepartmentid           
End          

-- Ref No	: 02 Commented
 --delete from #temp1 where companyid = @intcompanyid and accountid in (          
 --select distinct debtoraccid from acustomermaster)          

-- Ref No	: 02 Commented           
 --delete from #temp1 where companyid = @intcompanyid and accountid in (          
 --select distinct creditoraccid from avendormaster)          
          
 if @filtergroup >0            
 delete #temp1 from agroupmaster g, aaccountmaster m where #temp1.accountid = m.accountid          
 and m.groupid = g.groupid and g.groupid not in (@filtergroup)          
          
select @intcount = count(*) from #temp1          
          
          
while @intcount <> 0          
begin -- for while          
 select @intaccid = accountid, @straccdesc = accountdesc, @intAccCurrID=CurrencyID,          
 @straccounttype = type from #temp1          
          
 set @numDepbal =0.0          
     
 -- Ref No : 01 ----------start       
 /* SEEMS UNECESSARY       
 if @Depwise ='d'          
 Begin          
 exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,'dr', @numDepbal output, @intDepartmentID          
 End          
 else          
 Begin          
 exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,'cr', @numDepbal output, @intDepartmentID           
 End          
 */    
 ----- Ref No : 01 End    
     
 exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,'dr', @numDepbal output, @intDepartmentID      
 -- Ref No : 01 Start    
 -- IN OLD CODE SNIPPET IT WAS USED WRONG VARIABLE  @numDepbal to TO FIND BALANCE IN COMPANY CURR.     
 exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,'cr', @numconsbal output, @intDepartmentID    ---shine      
 -- Ref No : 01 End    
          
 set @numresbal =0.0          
 exec spopeningbalance_Adjustment @strcurdate, @intaccid, @intcompanyid,'ar', @numresbal output, @intDepartmentID          
        
 -- Ref No : 01 ----------start       
 /* SEEMS UNECESSARY        
 ----if @Depwise ='d'          
 ---- Begin          
 ----  exec spConvertequiamount @intAccCurrID, 'm', @intDepCurrID,           
 ----   'm', @strexrates , @numresbal, @numdepamount output,  'r'           
 ---- End          
 ----else          
 ----Begin          
 ---- exec spConvertequiamount @intAccCurrID, 'm', @intConsCurrID,           
 ----  'm', @strexrates , @numresbal, @numdepamount output,  'r'          
 ---- End           
       
 --exec spConvertequiamount @intAccCurrID, 'm', @intDepCurrID,           
 -- 'm', @strexrates , @numDepbal, @numdepamount output,  'r'      
  */    
 ----- Ref No : 01 End    
     
 exec spConvertequiamount @intDepCurrID, 'm', @intConsCurrID,           
 'm', @strexrates , @numDepbal, @numdepamount output,  'r'         
         
    exec spConvertequiamount @intConsCurrID, 'm', @intDepCurrID,        
    'm', @strexrates ,@numconsbal , @numConsamount output,  'r'         
          
-- Ref No : 01 ----------start        
     exec spConvertequiamount @intAccCurrID, 'm', @intConsCurrID,        
    'm', @strexrates ,@numresbal , @numresamountinConsCurr output,  'r'       
 ----- Ref No : 01 End    
 
 
 -- Ref No	: 02 Commented Below start
       
 ----   if abs(@numconsbal - (@numdepamount)) >= 1 -- this has the exchange difference              
 ----begin              
 ---- if ((@numconsbal > @numdepamount))              
 ----  set @bitjournalcredit = 0           
              
 ---- if ((@numconsbal < @numdepamount))              
 ----  set @bitjournalcredit =1        
 -- Ref No	: 02 Commented End
       
       
   
   -- Ref No	: 02 Added Below start  
  if abs(@numconsbal - (@numdepamount)) >= 1 -- this has the exchange difference        
   BEGIN            
      if ((@numconsbal > @numdepamount) and (@straccounttype ='a' or @straccounttype ='e'))          
       set @bitjournalcredit =0                    
      if ((@numconsbal < @numdepamount) and (@straccounttype ='a' or @straccounttype ='e'))          
       set @bitjournalcredit =1          
      if ((@numconsbal > @numdepamount) and (@straccounttype ='l' or @straccounttype ='i'))          
       set @bitjournalcredit =1          
      if ((@numconsbal < @numdepamount) and (@straccounttype ='l' or @straccounttype ='i'))          
       set @bitjournalcredit =0        

           ---           Ref No	: 02 end
      
       
       
   /*    
  if abs(@numresbal - (@numConsamount)) >= 1 -- this has the exchange difference        
   BEGIN      
          
      if ((@numConsamount > @numresamountinConsCurr) and (@straccounttype ='a' or @straccounttype ='e'))          
       set @bitjournalcredit =0                    
      if ((@numConsamount < @numresamountinConsCurr) and (@straccounttype ='a' or @straccounttype ='e'))          
       set @bitjournalcredit =1          
      if ((@numConsamount > @numresamountinConsCurr) and (@straccounttype ='l' or @straccounttype ='i'))          
       set @bitjournalcredit =1          
      if ((@numConsamount < @numresamountinConsCurr) and (@straccounttype ='l' or @straccounttype ='i'))          
       set @bitjournalcredit =0        
           
         
   */      
   set @numdiffamt  = abs(@numconsbal - @numdepamount)      
       
     exec spConvertequiamount @intConsCurrID, 'm', @intDepCurrID,      
   'm', @strexrates , @numdiffamt, @numConsamount output,  'r'     
      
 -- Ref No : 01 ----------start       
 /* SEEMS UNECESSARY     
            
  --exec spConvertequiamount @intConsCurrID, 'm', @intDepCurrID,      
  -- 'm', @strexrates , @numdiffamt, @numConsamount output,  'r'           
   */    
 ----- Ref No : 01 End       
       
   insert into #temp2 values (@intcompanyid, @intaccid, @straccdesc, @numDepbal,           
   @numConsbal,@numresbal,@numConsamount, @numdiffamt,@numresamountinConsCurr, @bitjournalcredit)          
 END         
       
         
 -- Ref No : 01 ----------start Commented and new snippet added above         
 /*      
 if abs(@numDepbal - (@numdepamount)) >= 1 -- this has the exchange difference          
 begin          
  if ((@numdepamount > @numDepbal) and (@straccounttype ='a' or @straccounttype ='e'))          
   set @bitjournalcredit =0          
          
  if ((@numdepamount < @numDepbal) and (@straccounttype ='a' or @straccounttype ='e'))          
   set @bitjournalcredit =1          
  if ((@numdepamount > @numDepbal) and (@straccounttype ='l' or @straccounttype ='i'))          
   set @bitjournalcredit =1          
  if ((@numdepamount < @numDepbal) and (@straccounttype ='l' or @straccounttype ='i'))          
   set @bitjournalcredit =0          
          
  set @numdiffamt  = abs(@numdepamount - @numDepbal)          
          
  if @Depwise ='d'          
  Begin          
   exec spConvertequiamount @intDepCurrID, 'm', @intConsCurrID,           
   'm', @strexrates , @numdiffamt, @numConsamount output,  'r'           
   insert into #temp2 values (@intcompanyid, @intaccid, @straccdesc,           
   @numDepbal, @numConsbal,@numresbal,@numdepamount, @numConsamount, @bitjournalcredit)          
  ENd          
  else          
  Begin          
   exec spConvertequiamount @intConsCurrID, 'm', @intDepCurrID,           
   'm', @strexrates , @numdiffamt, @numConsamount output,  'r'           
   insert into #temp2 values (@intcompanyid, @intaccid, @straccdesc, @numDepbal,           
   @numConsbal,@numresbal,@numConsamount , @numdepamount, @bitjournalcredit)          
  End          
 end           
 ----- Ref No : 01 End      
 */      
       
-- select * from #temp1          
 delete from #temp1 where accountid = @intaccid          
 select @intcount = count(*) from #temp1          
end -- for while          
select * from #temp2 order by accountdesc asc          
set nocount off          
end 
GO
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_047, M_189, M_237
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
use adminv2;
go
if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'spUpdateLedgersAssetDisposal' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE spUpdateLedgersAssetDisposal
end
GO
-- Modified by : Hariharan R, Hariharan R   
-- Modified on : 04/03/2004, 07/04/2004, 16/04/2004  
-- Comments    : Incremented the @intJournalDetailId after inserting to moaJournalDetails  
--        : Depreciation Exp AccId is used to get the disposal control account from asettings   
--             : Given postgroup columns  
------------------------------------------------------------------------------  
/*
Ref No : 101	
Modified By		: Shine Das
Modified On		: 23.05.2012
Desription		: Asset Disposal posting was wrong. Modification done for Correcting it.
*/
CREATE procedure spUpdateLedgersAssetDisposal @intdisposalid as int ,  
     @intcompanyid as int as   
begin   
  Declare   
 @intJournalID as int,  
 @dtdisphdate as datetime,  
 @strdisphremarks as varchar(250),  
 @strdisphauthorisedby as varchar(250),  
 @strRemarks as varchar(250),  
 @intFinancialID as int,  
 @intdepid as int,  
 @numconsrate as numeric(18,8),  
 @numdepRate as numeric(18,8),  
 @strexrates as varchar(250),  
 @intJournalDetailID as int,  
 @intassetid as int,  
 @numDebitAmt as numeric(18,2),   
 @intassetaccountid as int,  
 @intassetcreditaccountid as int,  
 @intAccumDepaccid as int,   
 @intDiposalAccId as int,   
 @intDepExpAccId as int,   
 @strdisphno as varchar(50),  
 @numaccamt as numeric(18,2),   
 @numDispSalesValue numeric(18,2),   
 @numUPTODepValue  as numeric(18,2),   
 @numDisDepeBalamt as numeric(18,2),   
 @intDepExpControlAccId as int,
 @intGainOrLossOnDisposalAccId as int, ---Ref No : 101	
 @strGainLossAccountType as varchar(50),  ---Ref No : 101
 @intProfitOrLossJournalCredit as INT,	 ---Ref No : 101
 @numProfitOrLossOnSale as numeric(18,2)  ---Ref No : 101	
  
   -----> Ref No : 101 Added "@intGainOrLossOnDisposalAccId"
 Select @intDepExpControlAccId = ISNULL(depriciationexpaccid,0),
 @intGainOrLossOnDisposalAccId=ISNULL(GainOrLossOnAssetDisposal,0) from aSettings where Companyid = @intCompanyId   
 
 -----> Ref No : 101 Checks both accounts are selected for posting or not
 IF @intDepExpControlAccId < 1 OR @intGainOrLossOnDisposalAccId < 1 
 BEGIN
  RETURN ----> If any one of the accounts are not selected then posting should be avoided
 END 
 
-----> Ref No : 101 Added to find Gain or Loss Account Type. Start
 select @strGainLossAccountType = Accounttype from aGroupMaster where GroupID in
(select GroupID from aAccountMaster where AccountID = @intGainOrLossOnDisposalAccId)
-----> Ref No : 101 End

 -----> Ref No : 101	Commented Start
 --Select @intDepExpControlAccId = depriciationexpaccid from aSettings where   
 --Companyid = @intCompanyId   
 -----> End 
  
 SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader WHERE   
 CompanyID = @intCompanyID  
   
 SELECT @strdisphno=disphno,@dtdisphdate=disphdate ,  
 @strdisphremarks=disphremarks ,@strdisphauthorisedby = disphauthorisedby,   
 @strRemarks =disphremarks, @intFinancialID = FinancialID,   
 @intdepid = disphdepartmentid, @numconsrate =disphexrate, @numdepRate = disphdepexrate,    
 @strexrates = disphexchangerates FROM AssetDisposalHeader  WHERE disphposted =0 and   
 disphcompanyid =  @intCompanyID and disphid=@intdisposalid  

 set @intJournalDetailID = 1  
 set @intJournalID = @intJournalID + 1   
 begin  

  
  insert into moajournalheader (JournalID, CompanyID, JournalDate,referenceno,  
  remarks, financialID,Type,chequedate)  
  values (@intJournalID, @intCompanyID,@dtdisphdate,@strdisphno,   
         @strRemarks, @intFinancialID, 'ASD', @dtdisphdate)     

  
  Declare DebitassetdisposalCur cursor for  
  SELECT dispdasstid, dispdaccid, dispdamount, disdepeBalamt, DisAstSaleValue,  
  disUptoDepAmt, isnull(lasttoaccid, FixedAssetAccID) assetaccid,  
  isnull(CurrAccDepExpAccID, DepreciationAccId) AccumDepAccId,   
  isnull(CurrDeprecExpAccID, depriciationexpaccid) DepExpAccID   
   FROM AssetDisposaldetail dp , FixedAsset fa   
  WHERE dispdcompanyid = @intCompanyID and dispID = @intdisposalid  
  and dispdasstid = fa.FixedAssetID and dispdcompanyid = fa.CompanyID  
  
  open DebitassetdisposalCur  
  fetch next FROM DebitassetdisposalCur into @intassetid,@intDiposalAccId,   
  @numDebitAmt, @numDisDepeBalamt, @numDispSalesValue, @numUPTODepValue,  
  @intassetaccountid, @intAccumDepaccid, @intDepExpAccId  
 
  
  while @@Fetch_status =0  
  begin  
       
   exec spConvertequiamount @intdepid, 'd',   
   @intassetaccountid, 'a', @strexrates,  
   @numDebitAmt , @numaccamt output     
   
   insert into moajournaldetails(JournalID, journaldetailID, CompanyID,  
   JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount,   
   PostGroup)   
   values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,   
   @intassetaccountid, @numDebitAmt  * @numconsrate, @numaccamt,   
   @intDepID, @numDebitAmt  * @numdeprate, 1)  
   
   set @intJournalDetailID = @intJournalDetailID + 1      
  
   exec spConvertequiamount @intdepid, 'd',   
   @intDiposalAccId, 'a', @strexrates,  
   @numDebitAmt , @numaccamt output     
          
   insert into moajournaldetails(JournalID, journaldetailID, CompanyID,  
   JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)   
   values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,   
   @intDiposalAccId, @numDebitAmt  * @numconsrate, @numaccamt,   
   @intDepID, @numDebitAmt  * @numdeprate, 1)  
  
   --if @numDisDepeBalamt <> 0   '---Ref No : 101	Commented
   if @numUPTODepValue <> 0 ---Ref No : 101	 Added
		   Begin  
		   set @intJournalDetailID = @intJournalDetailID + 1  
		  
		   --FOR POSTING REMAINING DEPRECIATION -------------------------------->    ---Ref No : 101 Commented
		   --exec spConvertequiamount @intdepid, 'd',   
		   --@intAccumDepaccid, 'a', @strexrates,  
		   --@numDisDepeBalamt , @numaccamt output    
		   
   		   -------------------------------->    ---Ref No : 101 Added
   		   exec spConvertequiamount @intdepid, 'd',   
		   @intAccumDepaccid, 'a', @strexrates,  
		   @numUPTODepValue , @numaccamt output   
		   
		   insert into moajournaldetails(JournalID, journaldetailID, CompanyID,  
		   JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount,   
		   PostGroup)   
		   values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,   
		   @intAccumDepaccid, @numUPTODepValue  * @numconsrate, @numaccamt,   
		   @intDepID, @numUPTODepValue * @numdeprate, 2)  
		   
		   set @intJournalDetailID = @intJournalDetailID + 1      
		  
		  -------------------------------->    ---Ref No : 101 Commented
		   --exec spConvertequiamount @intdepid, 'd',   
		   --@intDepExpAccId, 'a', @strexrates,  
		   --@numDisDepeBalamt , @numaccamt output  
		   
		   -------------------------------->    ---Ref No : 101 Added
		    exec spConvertequiamount @intdepid, 'd',   
		   @intDiposalAccId, 'a', @strexrates,  
		   @numUPTODepValue , @numaccamt output    
		      
		          
		   insert into moajournaldetails(JournalID, journaldetailID, CompanyID,  
		   JournalCrEDit, AccountID, Amount, actualAmount,departmentid,   
		   depamount, PostGroup)   
		   values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,   
		   @intDiposalAccId, @numUPTODepValue * @numconsrate, @numaccamt,   
		   @intDepID, @numUPTODepValue * @numdeprate, 2)  
  
   End  
   --FOR POSTING REMAINING DEPRECIATION -------------------------------->  
    
   --<POSTING ACC DEP REVERSING VALUE FOR THE ASSET ---------------------  
    
   --set @numUPTODepValue = isnull(@numDisDepeBalamt,0) + isnull(@numUPTODepValue,0)  
   -------------------------------->    ---Ref No : 101 Commented Start
   ------------if @numUPTODepValue  <>0   
   ------------Begin  
   ----------------------------set @intJournalDetailID = @intJournalDetailID + 1      
  
   ----------------------------exec spConvertequiamount @intdepid, 'd',   
   ----------------------------@intDiposalAccId, 'a', @strexrates,  
   ----------------------------@numUPTODepValue , @numaccamt output     
          
   ----------------------------insert into moajournaldetails(JournalID, journaldetailID, CompanyID,  
   ----------------------------JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)   
   ----------------------------values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,   
   ----------------------------@intDiposalAccId, @numUPTODepValue * @numconsrate, @numaccamt,   
   ----------------------------@intDepID, @numUPTODepValue * @numdeprate, 3)  
  
   ----------------------------set @intJournalDetailID = @intJournalDetailID + 1   
  
   ----------------------------exec spConvertequiamount @intdepid, 'd',   
   ----------------------------@intAccumDepaccid, 'a', @strexrates,  
   ----------------------------@numUPTODepValue , @numaccamt output     
   
   ----------------------------insert into moajournaldetails(JournalID, journaldetailID, CompanyID,  
   ----------------------------JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount,   
   ----------------------------PostGroup)   
   ----------------------------values (@intJournalID, @intjournalDetailID, @intCompanyID,0 ,   
   ----------------------------@intAccumDepaccid, @numUPTODepValue * @numconsrate, @numaccamt,   
   ----------------------------@intDepID, @numUPTODepValue * @numdeprate, 3)  
  
   ------------End  
  -------------------------------->    ---Ref No : 101 Commented End
   --POSTING ACC DEP REVERSING VALUE FOR THE ASSET ----------------------->  
   --<POSTING OF SALES WHILE DISPOSING -----------------------------------   
  
   if  @numDispSalesValue <> 0   
	   Begin  
	   set @intJournalDetailID = @intJournalDetailID + 1    
	   exec spConvertequiamount @intdepid, 'd',   
	   @intDiposalAccId, 'a', @strexrates,  
		@numDispSalesValue , @numaccamt output,''     
	          
	   insert into MoaJournalDetails(JournalID, journaldetailID, CompanyID,  
	   JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)   
	   values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,   
	   @intDiposalAccId,  @numDispSalesValue * @numconsrate, @numaccamt,   
	   @intDepID,  @numDispSalesValue * @numdeprate, 4)  
	   
	   ------------------------------------>    ---Ref No : 101 Added
	   SET @numProfitOrLossOnSale =  @numDispSalesValue-(@numDebitAmt-@numUPTODepValue) 
 
	    IF ABS(@numProfitOrLossOnSale) <>0
	    BEGIN
		set @intJournalDetailID = @intJournalDetailID + 1   	
		if (@numProfitOrLossOnSale>0 and @strGainLossAccountType = 'I') OR (@numProfitOrLossOnSale<0 and @strGainLossAccountType = 'E')
		  		set @intProfitOrLossJournalCredit = 0
		if (@numProfitOrLossOnSale<0 and @strGainLossAccountType = 'I') OR (@numProfitOrLossOnSale>0 and @strGainLossAccountType = 'E')
			   set @intProfitOrLossJournalCredit = 1
			   SET @numProfitOrLossOnSale = ABS(@numProfitOrLossOnSale)	
			   
				   exec spConvertequiamount @intdepid, 'd',   
				   @intGainOrLossOnDisposalAccId, 'a', @strexrates, @numProfitOrLossOnSale , @numaccamt output,''
			   
						   insert into MoaJournalDetails(JournalID, journaldetailID, CompanyID,  
						   JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)   
						   values (@intJournalID, @intjournalDetailID, @intCompanyID, @intProfitOrLossJournalCredit,   
						   @intGainOrLossOnDisposalAccId,  @numProfitOrLossOnSale * @numconsrate, @numaccamt,   
						   @intDepID,  @numProfitOrLossOnSale * @numdeprate, 5)  
						   
						   --@intDiposalAccId
				 set @intJournalDetailID = @intJournalDetailID + 1   
				 exec spConvertequiamount @intdepid, 'd',   
				   @intDiposalAccId, 'a', @strexrates, @numProfitOrLossOnSale , @numaccamt output,''	
						   
						   insert into MoaJournalDetails(JournalID, journaldetailID, CompanyID,  
						   JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)   
						   values (@intJournalID, @intjournalDetailID, @intCompanyID, ABS(@intProfitOrLossJournalCredit-1),   
						   @intDiposalAccId,  @numProfitOrLossOnSale * @numconsrate, @numaccamt,   
						   @intDepID,  @numProfitOrLossOnSale * @numdeprate, 5)  	   
		 END
	   ----------------------------------->    ---Ref No : 101  end
	  
	   set @intJournalDetailID = @intJournalDetailID + 1   
	  
	   exec spConvertequiamount @intdepid, 'd',   
	   @intDepExpControlAccId, 'a', @strexrates,  
		@numDispSalesValue , @numaccamt output,''     
	   
	   insert into MoaJournalDetails(JournalID, journaldetailID, CompanyID,  
	   JournalCrEDit, AccountID, Amount, actualAmount,departmentid,   
	   depamount, PostGroup)   
	   values (@intJournalID, @intjournalDetailID, @intCompanyID, 0 ,   
	   @intDepExpControlAccId,  @numDispSalesValue * @numconsrate, @numaccamt,   
	   @intDepID,  @numDispSalesValue * @numdeprate, 4)  
  
   End   
  
   set @intJournalDetailID = @intJournalDetailID + 1   
   --<POSTING OF SALES WHILE DISPOSING -----------------------------------   
  
   Set @numDebitAmt = 0.0  
   Set @numDisDepeBalamt = 0.0  
   Set @numDispSalesValue = 0.0  
   Set @numUPTODepValue = 0.0  
  
  fetch next FROM DebitassetdisposalCur into @intassetid,@intDiposalAccId,   
  @numDebitAmt, @numDisDepeBalamt, @numDispSalesValue, @numUPTODepValue,  
  @intassetaccountid, @intAccumDepaccid, @intDepExpAccId  
  
  end    
 end    
 update AssetDisposalHeader set disphposted =1 WHERE disphcompanyid =  @intCompanyID   
 and disphid=@intdisposalid  
  
 close DebitassetdisposalCur   
 deallocate DebitassetdisposalCur  
     
end  
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
use adminv2;
go
if Exists(SELECT * FROM SYSOBJECTS
  WHERE NAME = 'spUpdateLedgersAssetDisposal' 
  AND TYPE= 'p')
begin
  DROP PROCEDURE spUpdateLedgersAssetDisposal
end
GO
-- Modified by : Hariharan R, Hariharan R   
-- Modified on : 04/03/2004, 07/04/2004, 16/04/2004  
-- Comments    : Incremented the @intJournalDetailId after inserting to moaJournalDetails  
--        : Depreciation Exp AccId is used to get the disposal control account from asettings   
--             : Given postgroup columns  
------------------------------------------------------------------------------  
/*
Ref No : 101	
Modified By		: Shine Das
Modified On		: 23.05.2012
Desription		: Asset Disposal posting was wrong. Modification done for Correcting it.
-------------------------------------------------------------
Ref No : 102
Modified By		: Shine Das
Modified On		: 01.06.2012
Desription		: Gain Or Loss from sales need not post against Asset Disposal Account
--------------------------------------------------------------------------------------
*/
CREATE procedure spUpdateLedgersAssetDisposal @intdisposalid as int ,  
     @intcompanyid as int as   
begin   
  Declare   
 @intJournalID as int,  
 @dtdisphdate as datetime,  
 @strdisphremarks as varchar(250),  
 @strdisphauthorisedby as varchar(250),  
 @strRemarks as varchar(250),  
 @intFinancialID as int,  
 @intdepid as int,  
 @numconsrate as numeric(18,8),  
 @numdepRate as numeric(18,8),  
 @strexrates as varchar(250),  
 @intJournalDetailID as int,  
 @intassetid as int,  
 @numDebitAmt as numeric(18,2),   
 @intassetaccountid as int,  
 @intassetcreditaccountid as int,  
 @intAccumDepaccid as int,   
 @intDiposalAccId as int,   
 @intDepExpAccId as int,   
 @strdisphno as varchar(50),  
 @numaccamt as numeric(18,2),   
 @numDispSalesValue numeric(18,2),   
 @numUPTODepValue  as numeric(18,2),   
 @numDisDepeBalamt as numeric(18,2),   
 @intDepExpControlAccId as int,
 @intGainOrLossOnDisposalAccId as int, ---Ref No : 101	
 @strGainLossAccountType as varchar(50),  ---Ref No : 101
 @intProfitOrLossJournalCredit as INT,	 ---Ref No : 101
 @numProfitOrLossOnSale as numeric(18,2)  ---Ref No : 101	
  
   -----> Ref No : 101 Added "@intGainOrLossOnDisposalAccId"
 Select @intDepExpControlAccId = ISNULL(depriciationexpaccid,0),
 @intGainOrLossOnDisposalAccId=ISNULL(GainOrLossOnAssetDisposal,0) from aSettings where Companyid = @intCompanyId   
 
 -----> Ref No : 101 Checks both accounts are selected for posting or not
 IF @intDepExpControlAccId < 1 OR @intGainOrLossOnDisposalAccId < 1 
 BEGIN
  RETURN ----> If any one of the accounts are not selected then posting should be avoided
 END 
 
-----> Ref No : 101 Added to find Gain or Loss Account Type. Start
 select @strGainLossAccountType = Accounttype from aGroupMaster where GroupID in
(select GroupID from aAccountMaster where AccountID = @intGainOrLossOnDisposalAccId)
-----> Ref No : 101 End

 -----> Ref No : 101	Commented Start
 --Select @intDepExpControlAccId = depriciationexpaccid from aSettings where   
 --Companyid = @intCompanyId   
 -----> End 
  
 SELECT @intJournalID = isnull(max(JournalID),0) FROM moajournalheader WHERE   
 CompanyID = @intCompanyID  
   
 SELECT @strdisphno=disphno,@dtdisphdate=disphdate ,  
 @strdisphremarks=disphremarks ,@strdisphauthorisedby = disphauthorisedby,   
 @strRemarks =disphremarks, @intFinancialID = FinancialID,   
 @intdepid = disphdepartmentid, @numconsrate =disphexrate, @numdepRate = disphdepexrate,    
 @strexrates = disphexchangerates FROM AssetDisposalHeader  WHERE disphposted =0 and   
 disphcompanyid =  @intCompanyID and disphid=@intdisposalid  

 set @intJournalDetailID = 1  
 set @intJournalID = @intJournalID + 1   
 begin  

  
  insert into moajournalheader (JournalID, CompanyID, JournalDate,referenceno,  
  remarks, financialID,Type,chequedate)  
  values (@intJournalID, @intCompanyID,@dtdisphdate,@strdisphno,   
         @strRemarks, @intFinancialID, 'ASD', @dtdisphdate)     

  
  Declare DebitassetdisposalCur cursor for  
  SELECT dispdasstid, dispdaccid, dispdamount, disdepeBalamt, DisAstSaleValue,  
  disUptoDepAmt, isnull(lasttoaccid, FixedAssetAccID) assetaccid,  
  isnull(CurrAccDepExpAccID, DepreciationAccId) AccumDepAccId,   
  isnull(CurrDeprecExpAccID, depriciationexpaccid) DepExpAccID   
   FROM AssetDisposaldetail dp , FixedAsset fa   
  WHERE dispdcompanyid = @intCompanyID and dispID = @intdisposalid  
  and dispdasstid = fa.FixedAssetID and dispdcompanyid = fa.CompanyID  
  
  open DebitassetdisposalCur  
  fetch next FROM DebitassetdisposalCur into @intassetid,@intDiposalAccId,   
  @numDebitAmt, @numDisDepeBalamt, @numDispSalesValue, @numUPTODepValue,  
  @intassetaccountid, @intAccumDepaccid, @intDepExpAccId  
 
  
  while @@Fetch_status =0  
  begin  
       
   exec spConvertequiamount @intdepid, 'd',   
   @intassetaccountid, 'a', @strexrates,  
   @numDebitAmt , @numaccamt output     
   
   insert into moajournaldetails(JournalID, journaldetailID, CompanyID,  
   JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount,   
   PostGroup)   
   values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,   
   @intassetaccountid, @numDebitAmt  * @numconsrate, @numaccamt,   
   @intDepID, @numDebitAmt  * @numdeprate, 1)  
   
   set @intJournalDetailID = @intJournalDetailID + 1      
  
   exec spConvertequiamount @intdepid, 'd',   
   @intDiposalAccId, 'a', @strexrates,  
   @numDebitAmt , @numaccamt output     
          
   insert into moajournaldetails(JournalID, journaldetailID, CompanyID,  
   JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)   
   values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,   
   @intDiposalAccId, @numDebitAmt  * @numconsrate, @numaccamt,   
   @intDepID, @numDebitAmt  * @numdeprate, 1)  
  
   --if @numDisDepeBalamt <> 0   '---Ref No : 101	Commented
   if @numUPTODepValue <> 0 ---Ref No : 101	 Added
		   Begin  
		   set @intJournalDetailID = @intJournalDetailID + 1  
		  
		   --FOR POSTING REMAINING DEPRECIATION -------------------------------->    ---Ref No : 101 Commented
		   --exec spConvertequiamount @intdepid, 'd',   
		   --@intAccumDepaccid, 'a', @strexrates,  
		   --@numDisDepeBalamt , @numaccamt output    
		   
   		   -------------------------------->    ---Ref No : 101 Added
   		   exec spConvertequiamount @intdepid, 'd',   
		   @intAccumDepaccid, 'a', @strexrates,  
		   @numUPTODepValue , @numaccamt output   
		   
		   insert into moajournaldetails(JournalID, journaldetailID, CompanyID,  
		   JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount,   
		   PostGroup)   
		   values (@intJournalID, @intjournalDetailID, @intCompanyID, 0,   
		   @intAccumDepaccid, @numUPTODepValue  * @numconsrate, @numaccamt,   
		   @intDepID, @numUPTODepValue * @numdeprate, 2)  
		   
		   set @intJournalDetailID = @intJournalDetailID + 1      
		  
		  -------------------------------->    ---Ref No : 101 Commented
		   --exec spConvertequiamount @intdepid, 'd',   
		   --@intDepExpAccId, 'a', @strexrates,  
		   --@numDisDepeBalamt , @numaccamt output  
		   
		   -------------------------------->    ---Ref No : 101 Added
		    exec spConvertequiamount @intdepid, 'd',   
		   @intDiposalAccId, 'a', @strexrates,  
		   @numUPTODepValue , @numaccamt output    
		      
		          
		   insert into moajournaldetails(JournalID, journaldetailID, CompanyID,  
		   JournalCrEDit, AccountID, Amount, actualAmount,departmentid,   
		   depamount, PostGroup)   
		   values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,   
		   @intDiposalAccId, @numUPTODepValue * @numconsrate, @numaccamt,   
		   @intDepID, @numUPTODepValue * @numdeprate, 2)  
  
   End  
   --FOR POSTING REMAINING DEPRECIATION -------------------------------->  
    
   --<POSTING ACC DEP REVERSING VALUE FOR THE ASSET ---------------------  
    
   --set @numUPTODepValue = isnull(@numDisDepeBalamt,0) + isnull(@numUPTODepValue,0)  
   -------------------------------->    ---Ref No : 101 Commented Start
   ------------if @numUPTODepValue  <>0   
   ------------Begin  
   ----------------------------set @intJournalDetailID = @intJournalDetailID + 1      
  
   ----------------------------exec spConvertequiamount @intdepid, 'd',   
   ----------------------------@intDiposalAccId, 'a', @strexrates,  
   ----------------------------@numUPTODepValue , @numaccamt output     
          
   ----------------------------insert into moajournaldetails(JournalID, journaldetailID, CompanyID,  
   ----------------------------JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)   
   ----------------------------values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,   
   ----------------------------@intDiposalAccId, @numUPTODepValue * @numconsrate, @numaccamt,   
   ----------------------------@intDepID, @numUPTODepValue * @numdeprate, 3)  
  
   ----------------------------set @intJournalDetailID = @intJournalDetailID + 1   
  
   ----------------------------exec spConvertequiamount @intdepid, 'd',   
   ----------------------------@intAccumDepaccid, 'a', @strexrates,  
   ----------------------------@numUPTODepValue , @numaccamt output     
   
   ----------------------------insert into moajournaldetails(JournalID, journaldetailID, CompanyID,  
   ----------------------------JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount,   
   ----------------------------PostGroup)   
   ----------------------------values (@intJournalID, @intjournalDetailID, @intCompanyID,0 ,   
   ----------------------------@intAccumDepaccid, @numUPTODepValue * @numconsrate, @numaccamt,   
   ----------------------------@intDepID, @numUPTODepValue * @numdeprate, 3)  
  
   ------------End  
  -------------------------------->    ---Ref No : 101 Commented End
   --POSTING ACC DEP REVERSING VALUE FOR THE ASSET ----------------------->  
   --<POSTING OF SALES WHILE DISPOSING -----------------------------------   
  
   if  @numDispSalesValue <> 0   
	   Begin  
	   set @intJournalDetailID = @intJournalDetailID + 1    
	   exec spConvertequiamount @intdepid, 'd',   
	   @intDiposalAccId, 'a', @strexrates,  
		@numDispSalesValue , @numaccamt output,''     
	          
	   insert into MoaJournalDetails(JournalID, journaldetailID, CompanyID,  
	   JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)   
	   values (@intJournalID, @intjournalDetailID, @intCompanyID, 1,   
	   @intDiposalAccId,  @numDispSalesValue * @numconsrate, @numaccamt,   
	   @intDepID,  @numDispSalesValue * @numdeprate, 4)  
	   
	   ------------------------------------>    ---Ref No : 101 Added
	   SET @numProfitOrLossOnSale =  @numDispSalesValue-(@numDebitAmt-@numUPTODepValue) 
 
	    IF ABS(@numProfitOrLossOnSale) <>0
	    BEGIN
		set @intJournalDetailID = @intJournalDetailID + 1   	
		if (@numProfitOrLossOnSale>0 and @strGainLossAccountType = 'I') OR (@numProfitOrLossOnSale<0 and @strGainLossAccountType = 'E')
		  		set @intProfitOrLossJournalCredit = 0
		if (@numProfitOrLossOnSale<0 and @strGainLossAccountType = 'I') OR (@numProfitOrLossOnSale>0 and @strGainLossAccountType = 'E')
			   set @intProfitOrLossJournalCredit = 1
			   SET @numProfitOrLossOnSale = ABS(@numProfitOrLossOnSale)	
			   
				   exec spConvertequiamount @intdepid, 'd',   
				   @intGainOrLossOnDisposalAccId, 'a', @strexrates, @numProfitOrLossOnSale , @numaccamt output,''
			   
						   insert into MoaJournalDetails(JournalID, journaldetailID, CompanyID,  
						   JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)   
						   values (@intJournalID, @intjournalDetailID, @intCompanyID, @intProfitOrLossJournalCredit,   
						   @intGainOrLossOnDisposalAccId,  @numProfitOrLossOnSale * @numconsrate, @numaccamt,   
						   @intDepID,  @numProfitOrLossOnSale * @numdeprate, 5)  
						   
				 /* Ref No : 102 Start
				 set @intJournalDetailID = @intJournalDetailID + 1   
				 exec spConvertequiamount @intdepid, 'd',   
				   @intDiposalAccId, 'a', @strexrates, @numProfitOrLossOnSale , @numaccamt output,''	
						   
						   insert into MoaJournalDetails(JournalID, journaldetailID, CompanyID,  
						   JournalCrEDit, AccountID, Amount, actualAmount,departmentid, depamount, PostGroup)   
						   values (@intJournalID, @intjournalDetailID, @intCompanyID, ABS(@intProfitOrLossJournalCredit-1),   
						   @intDiposalAccId,  @numProfitOrLossOnSale * @numconsrate, @numaccamt,   
						   @intDepID,  @numProfitOrLossOnSale * @numdeprate, 5)  	   
				 Ref No : 102 End  */		   
		 END
	   ----------------------------------->    ---Ref No : 101  end
	  
	   set @intJournalDetailID = @intJournalDetailID + 1   
	  
	   exec spConvertequiamount @intdepid, 'd',   
	   @intDepExpControlAccId, 'a', @strexrates,  
		@numDispSalesValue , @numaccamt output,''     
	   
	   insert into MoaJournalDetails(JournalID, journaldetailID, CompanyID,  
	   JournalCrEDit, AccountID, Amount, actualAmount,departmentid,   
	   depamount, PostGroup)   
	   values (@intJournalID, @intjournalDetailID, @intCompanyID, 0 ,   
	   @intDepExpControlAccId,  @numDispSalesValue * @numconsrate, @numaccamt,   
	   @intDepID,  @numDispSalesValue * @numdeprate, 4)  
  
   End   
  
   set @intJournalDetailID = @intJournalDetailID + 1   
   --<POSTING OF SALES WHILE DISPOSING -----------------------------------   
  
   Set @numDebitAmt = 0.0  
   Set @numDisDepeBalamt = 0.0  
   Set @numDispSalesValue = 0.0  
   Set @numUPTODepValue = 0.0  
  
  fetch next FROM DebitassetdisposalCur into @intassetid,@intDiposalAccId,   
  @numDebitAmt, @numDisDepeBalamt, @numDispSalesValue, @numUPTODepValue,  
  @intassetaccountid, @intAccumDepaccid, @intDepExpAccId  
  
  end    
 end    
 update AssetDisposalHeader set disphposted =1 WHERE disphcompanyid =  @intCompanyID   
 and disphid=@intdisposalid  
  
 close DebitassetdisposalCur   
 deallocate DebitassetdisposalCur  
     
end  
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spConvertCurrency]    Script Date: 04/21/2012 12:26:42 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spConvertCurrency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spConvertCurrency]
GO

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spConvertCurrency]    Script Date: 04/21/2012 12:26:42 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

     -------------------------------------------------------------------------------  
--Created on  : 30/11/2002  
--Created by : leo  
--Comments : to do the currency conversion, this formula is tested  
-------------------------------------------------------------------------------  
--Modified on  : 24/09/2003  
--Modified by : R Harikrishnan  
--Comments : changed the output parameter precesion to 4  
------------------------------------------------------------------------------- 
--RefNo-1                      
--Modified on  : 19/04/2012                  
--Modified by  : MANUNADH. U
--Comments     : Change the precision from 4 to 9. otherwise the output will round 
--				 in to 4 decimal places.This modofication is donefor the 
--				 Task No: M_111 & M_112 specified in the Magnolia Issue Tracking System
------------------------------------------------------------------------------      
CREATE proc [dbo].[spConvertCurrency]   
 @numfromer  as numeric(15,8),   
 @numtoer  as numeric(15,8),   
 @numAmount  as numeric(20,9),   --<<RefNo-1>>Change the precision from 4 to 9
 @numequiamount  as numeric(20,9) output --<<RefNo-1>>Change the precision from 4 to 9
as  
begin  
 set nocount on  
 set @numequiamount = round((@numtoer / @numfromer) * @numamount,9)   --<<RefNo-1>>Change the rounding from 4 to 9
 set nocount off  
end  
GO


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
