--fiesGO
--BUILD Ver 1
--Date of creation: 19.06.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
--VIEW		: FINDVIEW
--SP		: FINDSP
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
GO
USE adminv2
GO
--FINDTABLE
--TABLE CREATIONS AND ALTERATIONS

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

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

DECLARE @AliasId INT
SET @AliasId = 0
SELECT @AliasId = AliasId 
FROM aAlias 
WHERE AliasId = 1
IF @AliasId = 0
	BEGIN
		insert into aAlias values (1,1,'Shop','','Alias name for Shop')
	END
Go
DECLARE @AliasId INT
SET @AliasId = 0
SELECT @AliasId = AliasId 
FROM aAlias 
WHERE AliasId = 2
IF @AliasId = 0
	BEGIN
		insert into aAlias values (1,2,'Godown','','Alias name for Godown')

	END


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='apackagesettings' AND COLUMN_NAME='NeedApproval' ) 
BEGIN
ALTER TABLE [dbo].[apackagesettings] ADD [NeedApproval][bit] NOT NULL DEFAULT (0)
END


GO

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

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='apackagesettings' AND COLUMN_NAME='ProjectWiseDespatch' ) 
BEGIN
ALTER TABLE [dbo].[apackagesettings] ADD [ProjectWiseDespatch][bit] NULL 
END
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

alter table losgoodsreturnnotedetail alter  COLUMN   GRNDunitprice numeric(18,8)
go
alter table losgoodsreturnnotedetail alter  COLUMN   idItemTaxAmount numeric(18,8)
go

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

alter table losbookservicedetails alter  COLUMN   serinvhTaxamount numeric(18,8)
go
alter table losbookpartsreplacedetails alter  COLUMN   repbkinvhTaxamount numeric(18,8)
go
alter table losinvservicedetails alter  COLUMN serinvdItemTaxAmount numeric(18,8)
go
alter table losinvpartsreplacedetails alter  COLUMN   repinvdItemTaxAmount numeric(18,8)
go
alter table losinvoicedservicedetails alter  COLUMN   serinvdItemTaxAmount numeric(18,8)
go
alter table losInvoicedPartsReplacedetails alter  COLUMN   repinvdItemTaxAmount numeric(18,8)
go

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

USE [master]
GO

IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'Documents')
BEGIN

/****** Object:  Database [Documents]    Script Date: 07/18/2012 17:15:09 ******/
CREATE DATABASE [Documents] ON  PRIMARY 
( NAME = N'Documents', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Documents.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'Documents_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Documents_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)

END
GO


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

GO
USE [Documents]
GO
/****** Object:  User [admin]    Script Date: 10/15/2012 12:50:30 ******/
IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = N'admin')
DROP USER [admin]
GO
/****** Object:  User [admin]    Script Date: 10/15/2012 12:50:30 ******/
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'admin')
CREATE USER [admin] FOR LOGIN [admin] WITH DEFAULT_SCHEMA=[dbo]
GO



GO

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


USE [Documents]
GO
/****** Object:  Table [dbo].[Documents]    Script Date: 07/19/2012 11:31:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Documents]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Documents](
	[ApplicationName] [varchar](50) NOT NULL,
	[Interface] [varchar](50) NOT NULL,
	[TransactionNo] [varchar](50) NOT NULL,
	[TransactionID] [int] NOT NULL,
	[Date] [datetime] NOT NULL,
	[Filename] [varchar](200) NOT NULL,
	[TYPE] [nvarchar](50) NULL,
	[Description] [nvarchar](max) NULL,
	[Image] [image] NULL,
	[Username] [varchar](100) NULL,
	[UpdateTime] [nvarchar](50) NULL,
 CONSTRAINT [PK_Documents] PRIMARY KEY CLUSTERED 
(
	[ApplicationName] ASC,
	[Interface] ASC,
	[TransactionNo] ASC,
	[TransactionID] ASC,
	[Date] ASC,
	[Filename] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO


USE adminv2
GO

------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
GO
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='aHQPaymentVoucherHeader' AND COLUMN_NAME='phuserid' ) 
BEGIN
alter table aHQPaymentVoucherHeader add [phuserid] [int] NULL
END

GO
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='ausers' AND COLUMN_NAME='usersignature' ) 
BEGIN
alter table ausers add [usersignature] [image] NULL
END

GO

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='loPrePurchaseOrderHeader' AND COLUMN_NAME='pohuserid' ) 
BEGIN
alter table loPrePurchaseOrderHeader add [pohuserid] [int] NULL
END

GO

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='loPurchaseOrderHeader' AND COLUMN_NAME='pohUserID' ) 
BEGIN
alter table loPurchaseOrderHeader add [pohUserID] [int] NULL
END

GO
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
DECLARE @tillstatus_id INT
SET @tillstatus_id = 0
SELECT @tillstatus_id = tillstatus_id 
FROM tillstatusmaster 
WHERE tillstatus_id = 1
IF @tillstatus_id = 0
	BEGIN
		insert into tillstatusmaster values(1,'Ready')
	END
GO

DECLARE @tillstatus_id INT
SET @tillstatus_id = 0
SELECT @tillstatus_id = tillstatus_id 
FROM tillstatusmaster 
WHERE tillstatus_id = 2
IF @tillstatus_id = 0
	BEGIN
		insert into tillstatusmaster values(2,'Used')
	END
GO
DECLARE @tillstatus_id INT
SET @tillstatus_id = 0
SELECT @tillstatus_id = tillstatus_id 
FROM tillstatusmaster 
WHERE tillstatus_id = 3
IF @tillstatus_id = 0
	BEGIN
		insert into tillstatusmaster values(3,'Not Used')
	END
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Added missing table related to Expiry Email alert on 07.08.12
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ExpiryEmailSettings]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ExpiryEmailSettings](
	[DSN] [varchar](50)  NULL,
	[DbName] [varchar](50) NULL,
	[OdbcUser] [varchar](50) NULL,
	[OdbcPassword] [varchar](50) NULL,
	[SMTPhost] [varchar](50) NULL,
	[Port] [int] NULL,
	[UserName] [varchar](50) NULL,
	[DisplayName] [varchar](50) NULL,
	[EmailID] [varchar](50) NULL,
	[Password] [varchar](50) NULL,
	[GracePeriod] [int] NULL
) ON [PRIMARY]
END
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Missing table found in SIMDI 07.08.12
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
-- Table Structure
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[posShortCut]') AND type in (N'U'))
BEGIN 
CREATE TABLE [dbo].[posShortCut] (
   [ShortCut] [int] NOT NULL,
   [ItemId] [numeric] (18, 0) NOT NULL,
   [Barcode] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
)
END
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

 update losgoodsreturnnotedetail  set grndPackTypeId=inv.idPackingTypeID   
    from (
			select distinct
			ih.ihInvoiceID,ih.ihShopID,ih.ihDepartmentID,id.idItemID,id.idPackingTypeID,gh.GrnhGoodsreturnnoteID
			from losinvoiceheader  ih                  
			left join losinvoicedetail id                  
			on ih.ihInvoiceid=id.idInvoiceid and ih.ihshopid=id.idshopid                   
			left join ashops s on ih.ihshopid = s.shopid
			left join adepartmentmaster d on ih.ihDepartmentID=  d.departmentid                  

			inner join losgoodsreturnnoteheader  gh
			on gh.GrnhInvoiceID=ih.ihInvoiceID and ih.ihShopID=gh.grnhShopid
					 and ih.ihDepartmentID= gh.grnhDepartmentid
			inner join losgoodsreturnnotedetail gd on gh.GrnhGoodsreturnnoteID = gd.GRNDReturnNoteID 
			and gh.grnhShopid = gd.GRNDShopid
			and id.idItemID=gd.GRNDItemID 

			inner join ashops sh on  gh.grnhshopid = sh.shopid
			inner join adepartmentmaster d1  on grnhdepartmentid = d1.departmentid   
			where    
				ih.ihtype ='i' 
				and ihproforma=0 and ihcashinvoice=0 
				and gd.grndPackTypeId is null
	    ) Inv   
        where 
			losgoodsreturnnotedetail.GRNDItemID=inv.idItemID
		and losgoodsreturnnotedetail.GRNDShopid= inv.ihShopID
		and losgoodsreturnnotedetail.GRNDReturnNoteID = inv.GrnhGoodsreturnnoteID
	
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

USE [adminv2]
GO

 alter table LosGoodsReturnNoteDetail alter  COLUMN GRNDPackTypeId INT NOT NULL
go

USE [adminv2]
GO

/****** Object:  Index [PK_LosGoodsReturnNoteDetail]    Script Date: 08/13/2012 10:15:54 ******/
IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[LosGoodsReturnNoteDetail]') AND name = N'PK_LosGoodsReturnNoteDetail')
ALTER TABLE [dbo].[LosGoodsReturnNoteDetail] DROP CONSTRAINT [PK_LosGoodsReturnNoteDetail]
GO

USE [adminv2]
GO

/****** Object:  Index [PK_LosGoodsReturnNoteDetail]    Script Date: 08/13/2012 10:15:54 ******/
ALTER TABLE [dbo].[LosGoodsReturnNoteDetail] ADD  CONSTRAINT [PK_LosGoodsReturnNoteDetail] PRIMARY KEY NONCLUSTERED 
(
	[GRNDReturnNoteID] ASC,
	[GRNDItemID] ASC,
	[GRNDShopid] ASC,
	[GRNDPackTypeId]ASC
	
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Done for correcting the error in loading Service Invoice
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 78 and columnid=9
IF @intCount = 0
BEGIN
	insert into atablecolumns values
(78,9,'serinvhamount','Amount',	'Amount','numeric',45,0,1,1,'8A6965DA-7358-4D24-98E8-DC619AFE4B0F')  
END
GO
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 78 and columnid=10
IF @intCount = 0
BEGIN
insert into atablecolumns values
(78,10,'serinvcancelled','Cancelled',	'Cancelled','numeric',15,0,1,1,newid())

END
GO
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 78 and columnid=11
IF @intCount = 0
BEGIN
insert into atablecolumns values
(78,11,'serinvposted','posted',	'posted','numeric',15,0,1,1,newid())

END

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Query given by Jyothish on 14.08.12 for upgradation purpose
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

/****** Object:  Table [dbo].[loPurchaseOrderQuatationDetails]    Script Date: 08/14/2012 14:33:38 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[loPurchaseOrderQuatationDetails]') AND type in (N'U'))
BEGIN 
CREATE TABLE [dbo].[loPurchaseOrderQuatationDetails](
	[CompanyID] [int] NULL,
	[DeptID] [int] NULL,
	[pohPOID] [int] NULL,
	[QuatationID] [int] NULL
) ON [PRIMARY]
END
GO

IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
WHERE  TABLE_NAME='Ashopsalespersondetails' AND COLUMN_NAME='userId') 
BEGIN
alter table Ashopsalespersondetails add userId  int
END
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID: 
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
/****** Objekt:  Table [dbo].[Projects]    ******/
USE [adminv2]
Go
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Projects]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Projects](
	[ItemKey] [uniqueidentifier] NOT NULL,
	[ItemText] [nvarchar](255) COLLATE Latin1_General_CI_AS NULL,
	[Description] [ntext] COLLATE Latin1_General_CI_AS NULL,
	[Properties] [xml] NULL,
	[Granularity] [smallint] NOT NULL,
	[MinMaxLinesVisible] [bit] NOT NULL CONSTRAINT [DF_Projects_MinMaxLinesVisible]  DEFAULT ((1)),
	[MinMaxLineStyle] [xml] NOT NULL,
	[TodayLineVisible] [bit] NOT NULL CONSTRAINT [DF_Projects_TodayLineVisible]  DEFAULT ((1)),
	[TodayLineStyle] [xml] NOT NULL,
	[ShowWeekends] [bit] NOT NULL CONSTRAINT [DF_Projects_ShowWeekends]  DEFAULT ((1)),
	[WeekendFormatStyle] [xml] NOT NULL,
	[ShowWorkingHours] [bit] NOT NULL CONSTRAINT [DF_Projects_ShowWorkingHours]  DEFAULT ((1)),
	[ShowWeeks] [bit] NOT NULL CONSTRAINT [DF_Projects_ShowWeeks]  DEFAULT ((1)),
	[GridLines] [bit] NOT NULL CONSTRAINT [DF_Projects_GridLines]  DEFAULT ((0)),
	[GridLineStyle] [xml] NOT NULL,
	[DefaultBarFormatStyle] [xml] NOT NULL,
	[DefaultGroupLineStyle] [xml] NOT NULL,
	[ResourceBarStyle] [xml] NOT NULL,
	[RelationLineStyle] [xml] NOT NULL,
	[RelationLineArrowWidth] [int] NOT NULL,
	[ShowCriticalPath] [bit] NOT NULL CONSTRAINT [DF_Projects_ShowCriticalPath]  DEFAULT ((1)),
	[CriticalPathLineStyle] [xml] NOT NULL,
	[BarTooltips] [tinyint] NOT NULL,
	[ItemTextDisplay] [tinyint] NOT NULL,
	[BarStyle] [tinyint] NOT NULL,
	[BarHeight] [int] NOT NULL,
	[RowHeight] [int] NOT NULL,
	[PercentBarDeflateX] [int] NOT NULL,
	[PercentBarDeflateY] [int] NOT NULL,
	[RandomBarColors] [bit] NOT NULL CONSTRAINT [DF_Projects_RandomBarColors]  DEFAULT ((1)),
	[ResourceBarStyleMode] [tinyint] NOT NULL,
	[ResourceViewFilter] [tinyint] NOT NULL,
	[ResourceStandardColor] [xml] NOT NULL,
	[ResourceOverloadColor] [xml] NOT NULL,
	[ResourceUnderloadColor] [xml] NOT NULL,
	[ShowIcons] [bit] NOT NULL CONSTRAINT [DF_Projects_ShowIcons]  DEFAULT ((0)),
	[ShowPriorityIcons] [bit] NOT NULL CONSTRAINT [DF_Projects_ShowPriorityIcons]  DEFAULT ((0)),
	[ShowStatusIcons] [bit] NOT NULL CONSTRAINT [DF_Projects_ShowStatusIcons]  DEFAULT ((0)),
	[ShowOverDueIcon] [bit] NOT NULL CONSTRAINT [DF_Projects_ShowOverDueIcon]  DEFAULT ((0)),
	[ShowHappinessIcon] [bit] NOT NULL CONSTRAINT [DF_Projects_ShowHappinessIcon]  DEFAULT ((0)),
	[ShowAlignmentIcon] [bit] NOT NULL CONSTRAINT [DF_Projects_ShowAlignmentIcon]  DEFAULT ((0)),
	[ShowCustomIcons] [bit] NOT NULL CONSTRAINT [DF_Projects_ShowCustomIcons]  DEFAULT ((0)),
	[StartDate] [datetime] NOT NULL,
	[EndDate] [datetime] NOT NULL,
	[DefaultTaskType] [tinyint] NOT NULL,
	[DefaultDurationType] [tinyint] NOT NULL,
	[NewTaskCount] [int] NOT NULL CONSTRAINT [DF_Projects_NewTaskCount]  DEFAULT ((0)),
	[ColorCyclerCurrentIndex] [int] NOT NULL CONSTRAINT [DF_Projects_ColorCyclerCurrentIndex]  DEFAULT ((0)),
	[ScrollOffsetY] [int] NOT NULL CONSTRAINT [DF_Projects_ScrollOffsetY]  DEFAULT ((0)),
	[ResourceBarColorTolerance] [real] NOT NULL CONSTRAINT [DF_Projects_ResourceBarColorTolerance]  DEFAULT ((0.1)),
 CONSTRAINT [PK_Projects] PRIMARY KEY CLUSTERED 
(
	[ItemKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
/****** Objekt:  Table [dbo].[ResourceAllocations]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ResourceAllocations]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ResourceAllocations](
	[ResourceKey] [uniqueidentifier] NOT NULL,
	[TaskKey] [uniqueidentifier] NOT NULL,
	[TaskCalendarKey] [uniqueidentifier] NULL,
	[TaskCalendarCombinationMode] [tinyint] NOT NULL,
	[ProjectKey] [uniqueidentifier] NOT NULL,
	[StartDate] [datetime] NOT NULL,
	[EndDate] [datetime] NOT NULL,
	[Unit] [float] NOT NULL,
	[TaskText] [nvarchar](255) COLLATE Latin1_General_CI_AS NULL,
	[ProjectText] [nvarchar](255) COLLATE Latin1_General_CI_AS NULL,
 CONSTRAINT [PK_ResourceAllocations] PRIMARY KEY CLUSTERED 
(
	[ResourceKey] ASC,
	[TaskKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[ResourceAllocations]') AND name = N'IX_ResourceAllocations')
CREATE NONCLUSTERED INDEX [IX_ResourceAllocations] ON [dbo].[ResourceAllocations] 
(
	[StartDate] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[ResourceAllocations]') AND name = N'IX_ResourceAllocations_1')
CREATE NONCLUSTERED INDEX [IX_ResourceAllocations_1] ON [dbo].[ResourceAllocations] 
(
	[ProjectKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[ResourceAllocations]') AND name = N'IX_ResourceAllocations_2')
CREATE NONCLUSTERED INDEX [IX_ResourceAllocations_2] ON [dbo].[ResourceAllocations] 
(
	[TaskKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Objekt:  Table [dbo].[WorkPreferredResources]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[WorkPreferredResources]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[WorkPreferredResources](
	[WorkKey] [uniqueidentifier] NOT NULL,
	[ResourceKey] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_WorkPreferredResources] PRIMARY KEY CLUSTERED 
(
	[WorkKey] ASC,
	[ResourceKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[WorkPreferredResources]') AND name = N'IX_WorkPreferredResources')
CREATE NONCLUSTERED INDEX [IX_WorkPreferredResources] ON [dbo].[WorkPreferredResources] 
(
	[ResourceKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Objekt:  Table [dbo].[ResourceSkills]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ResourceSkills]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ResourceSkills](
	[ResourceKey] [uniqueidentifier] NOT NULL,
	[SkillKey] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_ResourceSkills] PRIMARY KEY CLUSTERED 
(
	[ResourceKey] ASC,
	[SkillKey] 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
/****** Objekt:  Table [dbo].[ResourceRelations]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ResourceRelations]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ResourceRelations](
	[TaskKey] [uniqueidentifier] NOT NULL,
	[ResourceKey] [uniqueidentifier] NOT NULL,
	[ProjectKey] [uniqueidentifier] NOT NULL,
	[Unit] [float] NOT NULL CONSTRAINT [DF_ResourceRelations_Unit]  DEFAULT ((1.0)),
	[ProposedUnit] [float] NOT NULL CONSTRAINT [DF_ResourceRelations_ProposedUnit]  DEFAULT ((-1.0)),
	[Responsible] [bit] NOT NULL CONSTRAINT [DF_Task2Resource_Responsible]  DEFAULT ((0)),
 CONSTRAINT [PK_Task2Resource] PRIMARY KEY CLUSTERED 
(
	[TaskKey] ASC,
	[ResourceKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[ResourceRelations]') AND name = N'IX_Task2Resource')
CREATE NONCLUSTERED INDEX [IX_Task2Resource] ON [dbo].[ResourceRelations] 
(
	[ResourceKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[ResourceRelations]') AND name = N'IX_Task2Resource_1')
CREATE NONCLUSTERED INDEX [IX_Task2Resource_1] ON [dbo].[ResourceRelations] 
(
	[ProjectKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Objekt:  Table [dbo].[CalendarExceptions]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CalendarExceptions]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[CalendarExceptions](
	[CalendarKey] [uniqueidentifier] NOT NULL,
	[ExceptionDate] [datetime] NOT NULL,
	[IsWorkingDay] [bit] NOT NULL CONSTRAINT [DF_CalendarExceptions_IsWorkingDay]  DEFAULT ((0))
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CalendarExceptions]') AND name = N'IX_CalendarExceptions')
CREATE NONCLUSTERED INDEX [IX_CalendarExceptions] ON [dbo].[CalendarExceptions] 
(
	[CalendarKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Objekt:  Table [dbo].[CalendarWorkingHours]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CalendarWorkingHours]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[CalendarWorkingHours](
	[CalendarKey] [uniqueidentifier] NOT NULL,
	[DayOfWeek] [tinyint] NOT NULL,
	[StartHour] [real] NOT NULL,
	[EndHour] [real] NOT NULL,
	[ExceptionDate] [datetime] NULL
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CalendarWorkingHours]') AND name = N'IX_CalendarWorkingHours')
CREATE NONCLUSTERED INDEX [IX_CalendarWorkingHours] ON [dbo].[CalendarWorkingHours] 
(
	[CalendarKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Objekt:  Table [dbo].[Works]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Works]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Works](
	[ItemKey] [uniqueidentifier] NOT NULL,
	[TaskKey] [uniqueidentifier] NOT NULL,
	[ProjectKey] [uniqueidentifier] NOT NULL,
	[ItemText] [nvarchar](255) COLLATE Latin1_General_CI_AS NULL,
	[Description] [ntext] COLLATE Latin1_General_CI_AS NULL,
	[WorkHours] [float] NOT NULL CONSTRAINT [DF_Works_WorkHours]  DEFAULT ((0)),
	[ProposedWorkHours] [float] NOT NULL CONSTRAINT [DF_Works_ProposedWorkHours]  DEFAULT ((-1.0)),
	[SkillKey] [uniqueidentifier] NULL,
	[MaxEntities] [int] NOT NULL CONSTRAINT [DF_Works_MaxEntities]  DEFAULT ((0)),
 CONSTRAINT [PK_Works] PRIMARY KEY CLUSTERED 
(
	[ItemKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Works]') AND name = N'IX_Works')
CREATE NONCLUSTERED INDEX [IX_Works] ON [dbo].[Works] 
(
	[TaskKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Works]') AND name = N'IX_Works_1')
CREATE NONCLUSTERED INDEX [IX_Works_1] ON [dbo].[Works] 
(
	[ProjectKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Objekt:  Table [dbo].[TaskRelations]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TaskRelations]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[TaskRelations](
	[TaskKey] [uniqueidentifier] NOT NULL,
	[DependingTaskKey] [uniqueidentifier] NOT NULL,
	[ProjectKey] [uniqueidentifier] NOT NULL,
	[DelayDays] [float] NOT NULL CONSTRAINT [DF_TaskRelations_DelayDays]  DEFAULT ((0)),
	[DelayDurationType] [tinyint] NOT NULL,
	[TaskRelationMode] [tinyint] NOT NULL,
	[TaskRelationType] [tinyint] NOT NULL,
 CONSTRAINT [PK_Task2Task] PRIMARY KEY CLUSTERED 
(
	[TaskKey] ASC,
	[DependingTaskKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TaskRelations]') AND name = N'IX_Task2Task')
CREATE NONCLUSTERED INDEX [IX_Task2Task] ON [dbo].[TaskRelations] 
(
	[ProjectKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Objekt:  Table [dbo].[Tasks]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Tasks]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Tasks](
	[ItemKey] [uniqueidentifier] NOT NULL,
	[ProjectKey] [uniqueidentifier] NOT NULL,
	[ItemText] [nvarchar](255) COLLATE Latin1_General_CI_AS NULL,
	[Description] [ntext] COLLATE Latin1_General_CI_AS NULL,
	[Visible] [bit] NOT NULL CONSTRAINT [DF_Tasks_Visible]  DEFAULT ((1)),
	[StartDate] [datetime] NOT NULL,
	[EndDate] [datetime] NOT NULL,
	[Properties] [xml] NULL,
	[FormatStyle] [xml] NULL,
	[ParentItemKey] [uniqueidentifier] NULL,
	[PercentDone] [real] NULL,
	[EarliestStartDate] [datetime] NULL,
	[LatestStartDate] [datetime] NULL,
	[EarliestEndDate] [datetime] NULL,
	[LatestEndDate] [datetime] NULL,
	[StartDateRule] [tinyint] NOT NULL,
	[EndDateRule] [tinyint] NOT NULL,
	[IsMilestone] [bit] NOT NULL CONSTRAINT [DF_Tasks_IsMilestone]  DEFAULT ((0)),
	[Priority] [tinyint] NOT NULL,
	[Status] [tinyint] NOT NULL,
	[TaskType] [tinyint] NOT NULL,
	[Estimated] [bit] NOT NULL CONSTRAINT [DF_Tasks_Estimated]  DEFAULT ((0)),
	[DurationType] [tinyint] NOT NULL,
	[DurationDays] [float] NOT NULL CONSTRAINT [DF_Tasks_DurationDays]  DEFAULT ((0)),
	[CalendarKey] [uniqueidentifier] NULL,
	[ProjectCalendarCombinationMode] [tinyint] NOT NULL,
	[ASAP] [bit] NOT NULL CONSTRAINT [DF_Tasks_ASAP]  DEFAULT ((0)),
 CONSTRAINT [PK_Tasks] PRIMARY KEY CLUSTERED 
(
	[ItemKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Tasks]') AND name = N'IX_Tasks')
CREATE NONCLUSTERED INDEX [IX_Tasks] ON [dbo].[Tasks] 
(
	[ProjectKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Objekt:  Table [dbo].[Resources]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Resources]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Resources](
	[ItemKey] [uniqueidentifier] NOT NULL,
	[ProjectKey] [uniqueidentifier] NULL,
	[ItemText] [nvarchar](255) COLLATE Latin1_General_CI_AS NULL,
	[Description] [ntext] COLLATE Latin1_General_CI_AS NULL,
	[Visible] [bit] NOT NULL CONSTRAINT [DF_Resources_Visible]  DEFAULT ((1)),
	[Properties] [xml] NULL,
	[ResourceType] [tinyint] NOT NULL,
	[Role] [nvarchar](255) COLLATE Latin1_General_CI_AS NULL,
	[CostPerDay] [money] NULL,
	[CalendarKey] [uniqueidentifier] NULL,
	[ProjectCalendarCombinationMode] [tinyint] NOT NULL,
	[TaskCalendarCombinationMode] [tinyint] NOT NULL,
 CONSTRAINT [PK_Resources] PRIMARY KEY CLUSTERED 
(
	[ItemKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Resources]') AND name = N'IX_Resources')
CREATE NONCLUSTERED INDEX [IX_Resources] ON [dbo].[Resources] 
(
	[ProjectKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Objekt:  Table [dbo].[Calendars]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Calendars]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Calendars](
	[ItemKey] [uniqueidentifier] NOT NULL,
	[ProjectKey] [uniqueidentifier] NULL,
	[ItemText] [nvarchar](255) COLLATE Latin1_General_CI_AS NULL,
	[Description] [ntext] COLLATE Latin1_General_CI_AS NULL,
	[InheritedCalendarKey] [uniqueidentifier] NULL,
	[IsResourceCalendar] [bit] NOT NULL CONSTRAINT [DF_Calendars_IsResourceCalendar]  DEFAULT ((0)),
	[IsTaskCalendar] [bit] NOT NULL CONSTRAINT [DF_Calendars_IsTaskCalendar]  DEFAULT ((0)),
	[HasWorkingHours] [bit] NOT NULL CONSTRAINT [DF_Calendars_InheritedWorkingDays]  DEFAULT ((0)),
	[WorkMonday] [bit] NOT NULL CONSTRAINT [DF_Calendars_WorkMonday]  DEFAULT ((0)),
	[WorkTuesday] [bit] NOT NULL CONSTRAINT [DF_Calendars_WorkTuesday]  DEFAULT ((0)),
	[WorkWednesday] [bit] NOT NULL CONSTRAINT [DF_Calendars_WorkWednesday]  DEFAULT ((0)),
	[WorkThursday] [bit] NOT NULL CONSTRAINT [DF_Calendars_WorkThursday]  DEFAULT ((0)),
	[WorkFriday] [bit] NOT NULL CONSTRAINT [DF_Calendars_WorkFriday]  DEFAULT ((0)),
	[WorkSaturday] [bit] NOT NULL CONSTRAINT [DF_Calendars_WorkSaturday]  DEFAULT ((0)),
	[WorkSunday] [bit] NOT NULL CONSTRAINT [DF_Calendars_WorkSunday]  DEFAULT ((0)),
 CONSTRAINT [PK_Calendars] PRIMARY KEY CLUSTERED 
(
	[ItemKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Calendars]') AND name = N'IX_Calendars')
CREATE NONCLUSTERED INDEX [IX_Calendars] ON [dbo].[Calendars] 
(
	[ProjectKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Objekt:  Table [dbo].[Skills]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Skills]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Skills](
	[ItemKey] [uniqueidentifier] NOT NULL,
	[ProjectKey] [uniqueidentifier] NULL,
	[ItemText] [nvarchar](255) COLLATE Latin1_General_CI_AS NULL,
	[Description] [ntext] COLLATE Latin1_General_CI_AS NULL,
	[Productivity] [float] NOT NULL CONSTRAINT [DF_Skills_Productivity]  DEFAULT ((1.0)),
 CONSTRAINT [PK_Skills] PRIMARY KEY CLUSTERED 
(
	[ItemKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Skills]') AND name = N'IX_Skills')
CREATE NONCLUSTERED INDEX [IX_Skills] ON [dbo].[Skills] 
(
	[ProjectKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Objekt:  Table [dbo].[Groups]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Groups]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Groups](
	[ItemKey] [uniqueidentifier] NOT NULL,
	[ProjectKey] [uniqueidentifier] NOT NULL,
	[ItemText] [nvarchar](255) COLLATE Latin1_General_CI_AS NULL,
	[Description] [ntext] COLLATE Latin1_General_CI_AS NULL,
	[Visible] [bit] NOT NULL CONSTRAINT [DF_Groups_Visible]  DEFAULT ((1)),
	[Properties] [xml] NULL,
	[FormatStyle] [xml] NULL,
	[ParentItemKey] [uniqueidentifier] NULL,
 CONSTRAINT [PK_Groups] PRIMARY KEY CLUSTERED 
(
	[ItemKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Groups]') AND name = N'IX_Groups')
CREATE NONCLUSTERED INDEX [IX_Groups] ON [dbo].[Groups] 
(
	[ProjectKey] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO
/****** Objekt:  Trigger [TRG_Tasks_TaskRelations_DependingTask]    Skriptdatum: 04/13/2011 11:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_Tasks_TaskRelations_DependingTask]'))
EXEC dbo.sp_executesql @statement = N'CREATE TRIGGER [dbo].[TRG_Tasks_TaskRelations_DependingTask]
   ON  [dbo].[Tasks]
   AFTER DELETE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	Delete From dbo.TaskRelations Where TaskRelations.DependingTaskKey IN (select itemkey from deleted)		

    -- Insert statements for trigger here

END
'
GO
/****** Objekt:  Check [CK_TaskRelations]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[CK_TaskRelations]') AND parent_object_id = OBJECT_ID(N'[dbo].[TaskRelations]'))
ALTER TABLE [dbo].[TaskRelations]  WITH CHECK ADD  CONSTRAINT [CK_TaskRelations] CHECK  (([TaskKey]<>[DependingTaskKey]))
GO
ALTER TABLE [dbo].[TaskRelations] CHECK CONSTRAINT [CK_TaskRelations]
GO
/****** Objekt:  ForeignKey [FK_ResourceAllocations_Projects]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ResourceAllocations_Projects]') AND parent_object_id = OBJECT_ID(N'[dbo].[ResourceAllocations]'))
ALTER TABLE [dbo].[ResourceAllocations]  WITH CHECK ADD  CONSTRAINT [FK_ResourceAllocations_Projects] FOREIGN KEY([ProjectKey])
REFERENCES [dbo].[Projects] ([ItemKey])
GO
ALTER TABLE [dbo].[ResourceAllocations] CHECK CONSTRAINT [FK_ResourceAllocations_Projects]
GO
/****** Objekt:  ForeignKey [FK_ResourceAllocations_Resources]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ResourceAllocations_Resources]') AND parent_object_id = OBJECT_ID(N'[dbo].[ResourceAllocations]'))
ALTER TABLE [dbo].[ResourceAllocations]  WITH CHECK ADD  CONSTRAINT [FK_ResourceAllocations_Resources] FOREIGN KEY([ResourceKey])
REFERENCES [dbo].[Resources] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ResourceAllocations] CHECK CONSTRAINT [FK_ResourceAllocations_Resources]
GO
/****** Objekt:  ForeignKey [FK_ResourceAllocations_Tasks]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ResourceAllocations_Tasks]') AND parent_object_id = OBJECT_ID(N'[dbo].[ResourceAllocations]'))
ALTER TABLE [dbo].[ResourceAllocations]  WITH CHECK ADD  CONSTRAINT [FK_ResourceAllocations_Tasks] FOREIGN KEY([TaskKey])
REFERENCES [dbo].[Tasks] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ResourceAllocations] CHECK CONSTRAINT [FK_ResourceAllocations_Tasks]
GO
/****** Objekt:  ForeignKey [FK_WorkPreferredResources_Resources]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_WorkPreferredResources_Resources]') AND parent_object_id = OBJECT_ID(N'[dbo].[WorkPreferredResources]'))
ALTER TABLE [dbo].[WorkPreferredResources]  WITH CHECK ADD  CONSTRAINT [FK_WorkPreferredResources_Resources] FOREIGN KEY([ResourceKey])
REFERENCES [dbo].[Resources] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[WorkPreferredResources] CHECK CONSTRAINT [FK_WorkPreferredResources_Resources]
GO
/****** Objekt:  ForeignKey [FK_WorkPreferredResources_Works]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_WorkPreferredResources_Works]') AND parent_object_id = OBJECT_ID(N'[dbo].[WorkPreferredResources]'))
ALTER TABLE [dbo].[WorkPreferredResources]  WITH CHECK ADD  CONSTRAINT [FK_WorkPreferredResources_Works] FOREIGN KEY([WorkKey])
REFERENCES [dbo].[Works] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[WorkPreferredResources] CHECK CONSTRAINT [FK_WorkPreferredResources_Works]
GO
/****** Objekt:  ForeignKey [FK_ResourceSkills_Resources]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ResourceSkills_Resources]') AND parent_object_id = OBJECT_ID(N'[dbo].[ResourceSkills]'))
ALTER TABLE [dbo].[ResourceSkills]  WITH CHECK ADD  CONSTRAINT [FK_ResourceSkills_Resources] FOREIGN KEY([ResourceKey])
REFERENCES [dbo].[Resources] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ResourceSkills] CHECK CONSTRAINT [FK_ResourceSkills_Resources]
GO
/****** Objekt:  ForeignKey [FK_ResourceSkills_Skills]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ResourceSkills_Skills]') AND parent_object_id = OBJECT_ID(N'[dbo].[ResourceSkills]'))
ALTER TABLE [dbo].[ResourceSkills]  WITH CHECK ADD  CONSTRAINT [FK_ResourceSkills_Skills] FOREIGN KEY([SkillKey])
REFERENCES [dbo].[Skills] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ResourceSkills] CHECK CONSTRAINT [FK_ResourceSkills_Skills]
GO
/****** Objekt:  ForeignKey [FK_ResourceRelations_Resources]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ResourceRelations_Resources]') AND parent_object_id = OBJECT_ID(N'[dbo].[ResourceRelations]'))
ALTER TABLE [dbo].[ResourceRelations]  WITH CHECK ADD  CONSTRAINT [FK_ResourceRelations_Resources] FOREIGN KEY([ResourceKey])
REFERENCES [dbo].[Resources] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ResourceRelations] CHECK CONSTRAINT [FK_ResourceRelations_Resources]
GO
/****** Objekt:  ForeignKey [FK_ResourceRelations_Tasks]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ResourceRelations_Tasks]') AND parent_object_id = OBJECT_ID(N'[dbo].[ResourceRelations]'))
ALTER TABLE [dbo].[ResourceRelations]  WITH CHECK ADD  CONSTRAINT [FK_ResourceRelations_Tasks] FOREIGN KEY([TaskKey])
REFERENCES [dbo].[Tasks] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ResourceRelations] CHECK CONSTRAINT [FK_ResourceRelations_Tasks]
GO
/****** Objekt:  ForeignKey [FK_CalendarExceptions_Calendars1]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_CalendarExceptions_Calendars1]') AND parent_object_id = OBJECT_ID(N'[dbo].[CalendarExceptions]'))
ALTER TABLE [dbo].[CalendarExceptions]  WITH NOCHECK ADD  CONSTRAINT [FK_CalendarExceptions_Calendars1] FOREIGN KEY([CalendarKey])
REFERENCES [dbo].[Calendars] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CalendarExceptions] CHECK CONSTRAINT [FK_CalendarExceptions_Calendars1]
GO
/****** Objekt:  ForeignKey [FK_CalendarWorkingHours_Calendars1]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_CalendarWorkingHours_Calendars1]') AND parent_object_id = OBJECT_ID(N'[dbo].[CalendarWorkingHours]'))
ALTER TABLE [dbo].[CalendarWorkingHours]  WITH NOCHECK ADD  CONSTRAINT [FK_CalendarWorkingHours_Calendars1] FOREIGN KEY([CalendarKey])
REFERENCES [dbo].[Calendars] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[CalendarWorkingHours] CHECK CONSTRAINT [FK_CalendarWorkingHours_Calendars1]
GO
/****** Objekt:  ForeignKey [FK_Works_Projects]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Works_Projects]') AND parent_object_id = OBJECT_ID(N'[dbo].[Works]'))
ALTER TABLE [dbo].[Works]  WITH CHECK ADD  CONSTRAINT [FK_Works_Projects] FOREIGN KEY([ProjectKey])
REFERENCES [dbo].[Projects] ([ItemKey])
GO
ALTER TABLE [dbo].[Works] CHECK CONSTRAINT [FK_Works_Projects]
GO
/****** Objekt:  ForeignKey [FK_Works_Skills]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Works_Skills]') AND parent_object_id = OBJECT_ID(N'[dbo].[Works]'))
ALTER TABLE [dbo].[Works]  WITH CHECK ADD  CONSTRAINT [FK_Works_Skills] FOREIGN KEY([SkillKey])
REFERENCES [dbo].[Skills] ([ItemKey])
GO
ALTER TABLE [dbo].[Works] CHECK CONSTRAINT [FK_Works_Skills]
GO
/****** Objekt:  ForeignKey [FK_Works_Tasks]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Works_Tasks]') AND parent_object_id = OBJECT_ID(N'[dbo].[Works]'))
ALTER TABLE [dbo].[Works]  WITH CHECK ADD  CONSTRAINT [FK_Works_Tasks] FOREIGN KEY([TaskKey])
REFERENCES [dbo].[Tasks] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Works] CHECK CONSTRAINT [FK_Works_Tasks]
GO
/****** Objekt:  ForeignKey [FK_TaskRelations_Tasks]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TaskRelations_Tasks]') AND parent_object_id = OBJECT_ID(N'[dbo].[TaskRelations]'))
ALTER TABLE [dbo].[TaskRelations]  WITH CHECK ADD  CONSTRAINT [FK_TaskRelations_Tasks] FOREIGN KEY([TaskKey])
REFERENCES [dbo].[Tasks] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[TaskRelations] CHECK CONSTRAINT [FK_TaskRelations_Tasks]
GO
/****** Objekt:  ForeignKey [FK_TaskRelations_Tasks1]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_TaskRelations_Tasks1]') AND parent_object_id = OBJECT_ID(N'[dbo].[TaskRelations]'))
ALTER TABLE [dbo].[TaskRelations]  WITH NOCHECK ADD  CONSTRAINT [FK_TaskRelations_Tasks1] FOREIGN KEY([DependingTaskKey])
REFERENCES [dbo].[Tasks] ([ItemKey])
GO
ALTER TABLE [dbo].[TaskRelations] NOCHECK CONSTRAINT [FK_TaskRelations_Tasks1]
GO
/****** Objekt:  ForeignKey [FK_Tasks_Projects]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Tasks_Projects]') AND parent_object_id = OBJECT_ID(N'[dbo].[Tasks]'))
ALTER TABLE [dbo].[Tasks]  WITH CHECK ADD  CONSTRAINT [FK_Tasks_Projects] FOREIGN KEY([ProjectKey])
REFERENCES [dbo].[Projects] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Tasks] CHECK CONSTRAINT [FK_Tasks_Projects]
GO
/****** Objekt:  ForeignKey [FK_Resources_Projects]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Resources_Projects]') AND parent_object_id = OBJECT_ID(N'[dbo].[Resources]'))
ALTER TABLE [dbo].[Resources]  WITH NOCHECK ADD  CONSTRAINT [FK_Resources_Projects] FOREIGN KEY([ProjectKey])
REFERENCES [dbo].[Projects] ([ItemKey])
GO
ALTER TABLE [dbo].[Resources] CHECK CONSTRAINT [FK_Resources_Projects]
GO
/****** Objekt:  ForeignKey [FK_Calendars_Projects]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Calendars_Projects]') AND parent_object_id = OBJECT_ID(N'[dbo].[Calendars]'))
ALTER TABLE [dbo].[Calendars]  WITH NOCHECK ADD  CONSTRAINT [FK_Calendars_Projects] FOREIGN KEY([ProjectKey])
REFERENCES [dbo].[Projects] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Calendars] NOCHECK CONSTRAINT [FK_Calendars_Projects]
GO
/****** Objekt:  ForeignKey [FK_Skills_Projects]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Skills_Projects]') AND parent_object_id = OBJECT_ID(N'[dbo].[Skills]'))
ALTER TABLE [dbo].[Skills]  WITH CHECK ADD  CONSTRAINT [FK_Skills_Projects] FOREIGN KEY([ProjectKey])
REFERENCES [dbo].[Projects] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Skills] CHECK CONSTRAINT [FK_Skills_Projects]
GO
/****** Objekt:  ForeignKey [FK_Groups_Projects]    Skriptdatum: 04/13/2011 11:26:04 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Groups_Projects]') AND parent_object_id = OBJECT_ID(N'[dbo].[Groups]'))
ALTER TABLE [dbo].[Groups]  WITH CHECK ADD  CONSTRAINT [FK_Groups_Projects] FOREIGN KEY([ProjectKey])
REFERENCES [dbo].[Projects] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Groups] CHECK CONSTRAINT [FK_Groups_Projects]
GO
--*****************************************************************
--*****************************************************************
GO
/****** Objekt:  Table [dbo].[ResourceSkills]    Skriptdatum: 04/09/2011 23:11:11 ******/
USE [adminv2]
Go
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ResourceSkills]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ResourceSkills](
	[ResourceKey] [uniqueidentifier] NOT NULL,
	[SkillKey] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK_ResourceSkills] PRIMARY KEY CLUSTERED 
(
	[ResourceKey] ASC,
	[SkillKey] 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

/****** Objekt:  ForeignKey [FK_ResourceSkills_Resources]    Skriptdatum: 04/09/2011 23:11:11 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ResourceSkills_Resources]') AND parent_object_id = OBJECT_ID(N'[dbo].[ResourceSkills]'))
ALTER TABLE [dbo].[ResourceSkills]  WITH CHECK ADD  CONSTRAINT [FK_ResourceSkills_Resources] FOREIGN KEY([ResourceKey])
REFERENCES [dbo].[Resources] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ResourceSkills] CHECK CONSTRAINT [FK_ResourceSkills_Resources]
GO
/****** Objekt:  ForeignKey [FK_ResourceSkills_Skills]    Skriptdatum: 04/09/2011 23:11:11 ******/
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ResourceSkills_Skills]') AND parent_object_id = OBJECT_ID(N'[dbo].[ResourceSkills]'))
ALTER TABLE [dbo].[ResourceSkills]  WITH CHECK ADD  CONSTRAINT [FK_ResourceSkills_Skills] FOREIGN KEY([SkillKey])
REFERENCES [dbo].[Skills] ([ItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ResourceSkills] CHECK CONSTRAINT [FK_ResourceSkills_Skills]
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE table_name='Projects' AND column_name='ResourceBarColorTolerance')
ALTER TABLE [Projects] Add [ResourceBarColorTolerance] [real] NOT NULL CONSTRAINT [DF_Projects_ResourceBarColorTolerance]  DEFAULT ((0.1))
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE table_name='ResourceRelations' AND column_name='ProposedUnit')
ALTER TABLE [ResourceRelations] Add [ProposedUnit] [float] NOT NULL CONSTRAINT [DF_ResourceRelations_ProposedUnit]  DEFAULT ((-1.0))
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE table_name='Works' AND column_name='ProposedWorkHours')
ALTER TABLE [Works] Add [ProposedWorkHours] [float] NOT NULL CONSTRAINT [DF_Works_ProposedWorkHours]  DEFAULT ((-1.0))
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE table_name='Projects' AND column_name='ShowHappinessIcon')
ALTER TABLE [Projects] Add [ShowHappinessIcon] [bit] NOT NULL CONSTRAINT [DF_Projects_ShowHappinessIcon]  DEFAULT ((0))
GO

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

USE [adminv2]
GO
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE table_name='Resources' AND column_name='ResourceID')
Alter table Resources add ResourceID int
Go
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE table_name='aPackagesettings' AND column_name='ActivateServiceResourceScheduling')
Alter table aPackagesettings add ActivateServiceResourceScheduling bit default 0 with values
Go
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE table_name='groups' AND column_name='Shopid')
Alter Table groups add Shopid int
Go
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE table_name='groups' AND column_name='Jobcardid')
Alter Table groups add Jobcardid int
Go
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE table_name='Tasks' AND column_name='ShopID')
Alter table Tasks add ShopID int
Go
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE table_name='Tasks' AND column_name='JobCardID')
Alter table Tasks add JobCardID int
Go
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE table_name='Tasks' AND column_name='ServiceID')
Alter table Tasks add ServiceID int
Go
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.Columns WHERE table_name='aservicemaster' AND column_name='serDefaultDurMin')
Alter table aservicemaster add serDefaultDurMin int
Go
/****** Object:  Table [dbo].[Projects]    Script Date: 07/12/2012 09:58:10 ******/

INSERT [dbo].[Projects] ([ItemKey], [ItemText], [Description], [Properties], [Granularity], [MinMaxLinesVisible], [MinMaxLineStyle], [TodayLineVisible], [TodayLineStyle], [ShowWeekends], [WeekendFormatStyle], [ShowWorkingHours], [ShowWeeks], [GridLines], [GridLineStyle], [DefaultBarFormatStyle], [DefaultGroupLineStyle], [ResourceBarStyle], [RelationLineStyle], [RelationLineArrowWidth], [ShowCriticalPath], [CriticalPathLineStyle], [BarTooltips], [ItemTextDisplay], [BarStyle], [BarHeight], [RowHeight], [PercentBarDeflateX], [PercentBarDeflateY], [RandomBarColors], [ResourceBarStyleMode], [ResourceViewFilter], [ResourceStandardColor], [ResourceOverloadColor], [ResourceUnderloadColor], [ShowIcons], [ShowPriorityIcons], [ShowStatusIcons], [ShowOverDueIcon], [ShowHappinessIcon], [ShowAlignmentIcon], [ShowCustomIcons], [StartDate], [EndDate], [DefaultTaskType], [DefaultDurationType], [NewTaskCount], [ColorCyclerCurrentIndex], [ScrollOffsetY], [ResourceBarColorTolerance]) VALUES (NEWID(), N'Service Schedule', NULL, N'<Properties><item><key><string>created</string></key><value><anyType xmlns:q1="http://www.w3.org/2001/XMLSchema" xmlns:d4p1="http://www.w3.org/2001/XMLSchema-instance" d4p1:type="q1:dateTime">2012-07-09T13:25:37.7216122+05:30</anyType></value></item><item><key><string>created by</string></key><value><anyType xmlns:q1="http://www.w3.org/2001/XMLSchema" xmlns:d4p1="http://www.w3.org/2001/XMLSchema-instance" d4p1:type="q1:string">sa</anyType></value></item><item><key><string>changed</string></key><value><anyType xmlns:q1="http://www.w3.org/2001/XMLSchema" xmlns:d4p1="http://www.w3.org/2001/XMLSchema-instance" d4p1:type="q1:dateTime">2012-07-11T18:12:45.6486908+05:30</anyType></value></item><item><key><string>changed by</string></key><value><anyType xmlns:q1="http://www.w3.org/2001/XMLSchema" xmlns:d4p1="http://www.w3.org/2001/XMLSchema-instance" d4p1:type="q1:string">admin</anyType></value></item></Properties>', 24, 1, N'<LineStyle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Color>128;0;0;255</Color><DashStyle>Dash</DashStyle><LineWidth>2</LineWidth></LineStyle>', 1, N'<LineStyle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Color>128;255;0;0</Color><DashStyle>Dash</DashStyle><LineWidth>2</LineWidth></LineStyle>', 1, N'<HeaderFormatStyle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackgroundStyle><Color>80;32;178;170</Color><ColorEffect>Window</ColorEffect><GlossGradient>false</GlossGradient></BackgroundStyle><ForegroundStyle><Font><FontFamily>Microsoft Sans Serif</FontFamily><GraphicsUnit>Point</GraphicsUnit><Size>9</Size><Style>Regular</Style></Font></ForegroundStyle><VerticalLineStyle><Color>LightGray</Color></VerticalLineStyle><TopLineStyle /><BottomLineStyle /></HeaderFormatStyle>', 1, 1, 0, N'<LineStyle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Color>ActiveCaption</Color><DashStyle>Dot</DashStyle></LineStyle>', N'<BarFormatStyle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackgroundStyle><Color>80;0;0;255</Color></BackgroundStyle><BorderStyle /><ForegroundStyle><Color>ControlText</Color><Font><FontFamily>Tahoma</FontFamily><GraphicsUnit>Point</GraphicsUnit><Size>8.25</Size><Style>Regular</Style></Font></ForegroundStyle><PercentBarFillStyle><Color>80;0;0;0</Color><Hatch>true</Hatch><HatchStyle>DarkVertical</HatchStyle></PercentBarFillStyle></BarFormatStyle>', N'<BarFormatStyle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackgroundStyle /><BorderStyle><Color>Black</Color><LineWidth>3</LineWidth></BorderStyle><ForegroundStyle><Font><FontFamily>Tahoma</FontFamily><GraphicsUnit>Point</GraphicsUnit><Size>8.25</Size><Style>Regular</Style></Font></ForegroundStyle><PercentBarFillStyle /></BarFormatStyle>', N'<BarFormatStyle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><BackgroundStyle><Color>80;0;0;255</Color></BackgroundStyle><BorderStyle /><ForegroundStyle><Color>ControlText</Color><Font><FontFamily>Tahoma</FontFamily><GraphicsUnit>Point</GraphicsUnit><Size>8.25</Size><Style>Regular</Style></Font></ForegroundStyle><PercentBarFillStyle><Color>80;0;0;0</Color><Hatch>true</Hatch><HatchStyle>DarkVertical</HatchStyle></PercentBarFillStyle></BarFormatStyle>', N'<LineStyle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Color>128;0;0;0</Color><LineWidth>2</LineWidth></LineStyle>', 8, 1, N'<LineStyle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Color>128;0;0;255</Color><LineWidth>2</LineWidth></LineStyle>', 5, 2, 0, 12, 24, 0, 8, 1, 0, 1, N'Blue', N'Red', N'Green', 0, 1, 1, 1, 0, 1, 1, CAST(0x0000A06B00B54640 AS DateTime), CAST(0x0000A0A800B54640 AS DateTime), 1, 0, 5, 9, 0, 0.1)
Go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM ainterface
WHERE InterfaceID = 1822
IF @intCount = 0
BEGIN
insert into ainterface values(1822,'Service Job Scheduling','pocR',0,1,NULL,newid(),Null)
END
Go
insert into Resources  (ItemKey, ProjectKey,ItemText,Description,Visible,Properties,ResourceType,Role,CostPerDay,
CalendarKey,ProjectCalendarCombinationMode,TaskCalendarCombinationMode,ResourceID) 
(select NEWID() ,NULL,Spername,NULL,1,NULL,0,0,0.00,NULL,0,0,Sperid from AsalesPersonmaster where Sperqualification='Technician')

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE adminv2
go
ALTER TABLE receiptvoucherheader ALTER COLUMN Remarks varchar(500)
GO
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:SZG-822188
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
alter table losLocalPurchaseDetail  ALTER COLUMN  lpdPOQuantity numeric (38,4)
go
alter table losLocalPurchaseDetail  ALTER COLUMN  lpdItemQuantity numeric (38,4)
go
alter table losLocalPurchaseDetail  ALTER COLUMN  lpdPOUnitPrice numeric (38,4)
go
alter table losLocalPurchaseDetail  ALTER COLUMN  lpdItemUnitPrice numeric (38,4)
go
alter table losLocalPurchaseDetail  ALTER COLUMN  lpdItemActualAmount numeric (38,4)
go
alter table losPurchaseOrderDetail  ALTER COLUMN  podQty numeric (38,4)
go
alter table losPurchaseOrderDetail  ALTER COLUMN  podUnitPrice numeric (38,4)
go
alter table losPurchaseOrderDetail  ALTER COLUMN  podActualAmt numeric (38,4)
go
alter table losPurchaseOrderDetail  ALTER COLUMN  podPackQty numeric (38,4)
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
alter table losgoodsreturnnotedetail alter  COLUMN   GRNDunitprice numeric(18,8)
go
alter table losgoodsreturnnotedetail alter  COLUMN   idItemTaxAmount numeric(18,8)
go
alter table losbookservicedetails alter  COLUMN   serinvhTaxamount numeric(18,8)
go
alter table losbookpartsreplacedetails alter  COLUMN   repbkinvhTaxamount numeric(18,8)
go
alter table losinvservicedetails alter  COLUMN serinvdItemTaxAmount numeric(18,8)
go
alter table losinvpartsreplacedetails alter  COLUMN   repinvdItemTaxAmount numeric(18,8)
go
alter table losinvoicedservicedetails alter  COLUMN   serinvdItemTaxAmount numeric(18,8)
go
alter table losInvoicedPartsReplacedetails alter  COLUMN   repinvdItemTaxAmount numeric(18,8)
go
alter table losspecialinvoicedetail alter column idUnitPrice numeric(18,8)
go
alter table losspecialinvoicedetail alter column idItemTaxAmount numeric(18,8)
go
alter table losInvoiceOC alter  COLUMN   ioServTaxAmount numeric(18,8)
go
alter table losposexchangeDetail alter  COLUMN   sedunitprice numeric(18,8)
go
alter table losposexchangeDetail alter  COLUMN   sedItemtaxamount numeric(18,8)
go

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:XLW-768367 
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

USE [adminv2]
GO
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='aShops' AND COLUMN_NAME='BlockSPcheckInInvoiceFromLP' ) 
Begin
	alter table aShops add BlockSPcheckInInvoiceFromLP bit default 0 with values
end  
GO
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='aShops' AND COLUMN_NAME='BlockQtyEditInInvoiceFromLP' ) 
Begin
	alter table aShops add BlockQtyEditInInvoiceFromLP bit default 0 with values
end 
GO
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='aShops' AND COLUMN_NAME='BlockSoldLPitemsInInvoice' ) 
Begin
	alter table aShops add BlockSoldLPitemsInInvoice bit default 0 with values
end 
GO

/****** Object:  Table [dbo].[LosLocalPurchaseInvoiceDetails]    Script Date: 09/05/2012 12:18:01 ******/

USE [adminv2]
GO

/****** Object:  Table [dbo].[LosLocalPurchaseInvoiceDetails]    Script Date: 09/05/2012 12:18:01 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[LosLocalPurchaseInvoiceDetails]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[LosLocalPurchaseInvoiceDetails](
	[lpidShopId] [int] NOT NULL,
	[lpidInvoiceId] [int] NOT NULL,
	[lpidBillId] [int] NOT NULL,
	[lpidItemId] [int] NOT NULL,
	[lpidPackingTypeId] [int] NOT NULL
) ON [PRIMARY]

end

GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:XLW-768367 
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
use adminv2
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM areports
WHERE ReportID = 7198 
IF @intCount = 0
BEGIN
	insert into areports values(7198,'Purchase And Sales Report','purchase&salesreport',3,1,'poscbRR',1)
END
GO


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

/****** Object:  Table [dbo].[loEmailalertTransactions]    Script Date: 07/28/2012 14:18:24 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[loEmailalertTransactions]') AND type in (N'U'))
BEGIN

CREATE TABLE [dbo].[loEmailalertTransactions](
	[InterfaceID] [int] NOT NULL,
	[InterfaceName] [nvarchar](50) NOT NULL,
	[IsShopTrans] [bit] NOT NULL,
 CONSTRAINT [PK_loEmailalertTransactions] PRIMARY KEY CLUSTERED 
(
	[InterfaceID] 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


USE [adminv2]
GO

/****** Object:  Table [dbo].[loEmailalertUsers]    Script Date: 07/28/2012 14:18:28 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[loEmailalertUsers]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[loEmailalertUsers](
	[InterfaceID] [int] NOT NULL,
	[FromShopID] [int] NOT NULL,
	[ToShopID] [int] NULL,
	[ToGodownID] [int] NULL,
	[UserID] [int] NOT NULL,
 CONSTRAINT [PK_loEmailalertUsers] PRIMARY KEY CLUSTERED 
(
	[InterfaceID] ASC,
	[FromShopID] ASC,
	[UserID] 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:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
use adminv2
go
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[aapprovalinterfaces]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[aapprovalinterfaces](
	[interfaceID] [int] NULL,
	[interfacename] [varchar](100) NULL
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[aApprovalTransactions]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[aApprovalTransactions](
	[interfaceid] [int] NOT NULL,
	[Active] [bit] NULL DEFAULT ((0)),
 CONSTRAINT [PK_aApprovalTransactions] PRIMARY KEY CLUSTERED 
(
	[interfaceid] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[aApprovalLevelMaster]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[aApprovalLevelMaster](
	[LevelID] [int] NOT NULL,
	[LevelNo] [int] NOT NULL,
	[LevelName] [varchar](100) NULL,
	[InterfaceID] [int] NOT NULL,
	[DepartmentID] [int] NOT NULL,
 CONSTRAINT [PK_aApprovalLevelMaster_1] PRIMARY KEY CLUSTERED 
(
	[LevelID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[aApprovalLimitMaster]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[aApprovalLimitMaster](
	[LimitID] [int] NOT NULL,
	[interfaceid] [int] NOT NULL,
	[LimitNo] [varchar](50) NOT NULL,
	[CurrencyID] [int] NULL,
	[UpperLimit] [numeric](18, 9) NULL,
	[LowerLimit] [numeric](18, 9) NULL,
	[DepartmentID] [int] NOT NULL,
 CONSTRAINT [PK_aApprovalLimitMaster] PRIMARY KEY CLUSTERED 
(
	[LimitID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[aApprovalUserGroupRights]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[aApprovalUserGroupRights](
	[UsergroupID] [int] NOT NULL,
	[ModuleCode] [varchar](10) NULL,
	[InterfaceID] [int] NOT NULL,
	[ApprovalRights] [int] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[rowguid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
 CONSTRAINT [PK_aApprovalUserGroupRights] PRIMARY KEY CLUSTERED 
(
	[UsergroupID] ASC,
	[InterfaceID] ASC,
	[ApprovalRights] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[aApprovalRollBackTrans]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[aApprovalRollBackTrans](
	[interfaceid] [int] NOT NULL,
	[transactionid] [int] NOT NULL,
	[approvalstatuslevel] [int] NOT NULL,
	[userid] [int] NULL,
	[rejected] [int] NULL,
	[RollBackdate] [datetime] NULL,
	[updatetime] [datetime] NULL,
	[RollBackReason] [varchar](200) NULL,
	[CompanyID] [int] NULL,
	[DepartmentID] [int] NOT NULL
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[aApprovalStatus]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[aApprovalStatus](
	[interfaceid] [int] NOT NULL,
	[transactionid] [int] NOT NULL,
	[approvalstatuslevel] [int] NOT NULL,
	[userid] [int] NULL,
	[approveddate] [datetime] NULL,
	[updatetime] [datetime] NULL,
	[RejectedReason] [varchar](200) NULL,
	[Rejected] [bit] NOT NULL,
	[CompanyID] [int] NOT NULL,
	[DepartmentID] [int] NOT NULL,
	[GodownID] [int] NULL,
	[ShopID] [int] NULL
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[aApprovalLevelLimits]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[aApprovalLevelLimits](
	[DepartmentID] [int] NOT NULL,
	[interfaceid] [int] NOT NULL,
	[LimitId] [int] NOT NULL,
	[LevelId] [int] NOT NULL
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_aApprovalTransactions_aApprovalTransactions]') AND parent_object_id = OBJECT_ID(N'[dbo].[aApprovalTransactions]'))
ALTER TABLE [dbo].[aApprovalTransactions]  WITH CHECK ADD  CONSTRAINT [FK_aApprovalTransactions_aApprovalTransactions] FOREIGN KEY([interfaceid])
REFERENCES [dbo].[aApprovalTransactions] ([interfaceid])
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_aApprovalLevelMaster_aApprovalTransactions]') AND parent_object_id = OBJECT_ID(N'[dbo].[aApprovalLevelMaster]'))
ALTER TABLE [dbo].[aApprovalLevelMaster]  WITH CHECK ADD  CONSTRAINT [FK_aApprovalLevelMaster_aApprovalTransactions] FOREIGN KEY([InterfaceID])
REFERENCES [dbo].[aApprovalTransactions] ([interfaceid])
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_aApprovalLimitMaster_aApprovalTransactions]') AND parent_object_id = OBJECT_ID(N'[dbo].[aApprovalLimitMaster]'))
ALTER TABLE [dbo].[aApprovalLimitMaster]  WITH CHECK ADD  CONSTRAINT [FK_aApprovalLimitMaster_aApprovalTransactions] FOREIGN KEY([interfaceid])
REFERENCES [dbo].[aApprovalTransactions] ([interfaceid])
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_aApprovalUserGroupRights_aApprovalTransactions]') AND parent_object_id = OBJECT_ID(N'[dbo].[aApprovalUserGroupRights]'))
ALTER TABLE [dbo].[aApprovalUserGroupRights]  WITH CHECK ADD  CONSTRAINT [FK_aApprovalUserGroupRights_aApprovalTransactions] FOREIGN KEY([InterfaceID])
REFERENCES [dbo].[aApprovalTransactions] ([interfaceid])
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_aApprovalRollBackTrans_aApprovalTransactions]') AND parent_object_id = OBJECT_ID(N'[dbo].[aApprovalRollBackTrans]'))
ALTER TABLE [dbo].[aApprovalRollBackTrans]  WITH CHECK ADD  CONSTRAINT [FK_aApprovalRollBackTrans_aApprovalTransactions] FOREIGN KEY([interfaceid])
REFERENCES [dbo].[aApprovalTransactions] ([interfaceid])
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_aApprovalStatus_aApprovalLevelMaster]') AND parent_object_id = OBJECT_ID(N'[dbo].[aApprovalStatus]'))
ALTER TABLE [dbo].[aApprovalStatus]  WITH CHECK ADD  CONSTRAINT [FK_aApprovalStatus_aApprovalLevelMaster] FOREIGN KEY([approvalstatuslevel])
REFERENCES [dbo].[aApprovalLevelMaster] ([LevelID])
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_aApprovalLevelLimits_aApprovalLimitMaster]') AND parent_object_id = OBJECT_ID(N'[dbo].[aApprovalLevelLimits]'))
ALTER TABLE [dbo].[aApprovalLevelLimits]  WITH CHECK ADD  CONSTRAINT [FK_aApprovalLevelLimits_aApprovalLimitMaster] FOREIGN KEY([LimitId])
REFERENCES [dbo].[aApprovalLimitMaster] ([LimitID])
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_aApprovalLevelLimits_aApprovalTransactions]') AND parent_object_id = OBJECT_ID(N'[dbo].[aApprovalLevelLimits]'))
ALTER TABLE [dbo].[aApprovalLevelLimits]  WITH CHECK ADD  CONSTRAINT [FK_aApprovalLevelLimits_aApprovalTransactions] FOREIGN KEY([LevelId])
REFERENCES [dbo].[aApprovalLevelMaster] ([LevelID])
go


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


use adminv2
go

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='aPAckageSettings' AND COLUMN_NAME='NeedApproval' ) 
Begin
	alter table aPAckageSettings add NeedApproval BIT  NOT null DEFAULT 0
end  
go

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='ausers' AND COLUMN_NAME='usersignature' ) 
Begin
	alter table ausers add usersignature image
end  
go

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='lopurchaseorderheader' AND COLUMN_NAME='pohuserid' ) 
Begin
	alter table lopurchaseorderheader add pohuserid int
end  
go

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='loPrePurchaseOrderHeader' AND COLUMN_NAME='pohuserid' ) 
Begin
	alter table loPrePurchaseOrderHeader add pohuserid int
end  
go

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='aHQPaymentVoucherHeader' AND COLUMN_NAME='phuserid' ) 
Begin
	alter table aHQPaymentVoucherHeader add phuserid int
end  
go

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='aPAckageSettings' AND COLUMN_NAME='ProjectWiseDespatch' ) 
Begin
	alter table aPAckageSettings add ProjectWiseDespatch bit
end  
go


IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='MeiGodownRequestDetail' AND COLUMN_NAME='GRDCostPrice' ) 
Begin
	alter table MeiGodownRequestDetail add GRDCostPrice NUMERIC(18,9)
end  

go
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='MeiGodownRequestHeader' AND COLUMN_NAME='GRHTotalCostPrice' ) 
Begin
	alter table MeiGodownRequestHeader add GRHTotalCostPrice NUMERIC(18,9)
end  
go

DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM ainterface
WHERE InterfaceID = 92034
IF @intCount = 0
BEGIN
insert into aInterface values(92034,'Approval Level Master','hqadm',0,1,null,newid(),null)
END
go


IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='aApprovalStatus' AND COLUMN_NAME='GodownID' ) 
Begin
	alter table aApprovalStatus add GodownID INT NULL
end  
go

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='aApprovalStatus' AND COLUMN_NAME='ShopID' ) 
Begin
	alter table aApprovalStatus add ShopID INT NULL
end  
go

DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM aTables
WHERE TableID = 251 
IF @intCount = 0
BEGIN
	INSERT INTO aTables VALUES(251,'aApprovalLevelMaster','Approval Level Master','Approval Level Master',1,newid())
END
GO

DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 251 and columnid=1
IF @intCount = 0
BEGIN
	INSERT INTO atablecolumns values(251,1,'LevelID','Level ID','Level ID','int',4,null,1,1,newid())
END
GO
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 251 and columnid=2
IF @intCount = 0
BEGIN
	INSERT INTO atablecolumns values(251,2,'DepartmentID','Department','Department','int',4,null,1,1,newid())
END
GO
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 251 and columnid=3
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(251,3,'InterfaceID','Interface','Interface','int',4,null,1,1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 251 and columnid=4
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(251,4,'LevelNo','Level No','Level No','int',4,null,1,1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 251 and columnid=5
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(251,5,'LevelName','Level Name','Level Name','varchar',100,null,1,1,newid())
END

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

DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM aInterface
WHERE InterfaceID = 92035
IF @intCount = 0
BEGIN
insert into aInterface values(92035,'Approval Limit Master','hqadm',0,1,null,newid(),null)
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM aTables
WHERE TableID = 252
IF @intCount = 0
BEGIN
INSERT INTO aTables VALUES(252,'aApprovalLimitMaster','Approval Limit Master','Approval Limit Master',1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 252 and columnid=1
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(252,1,'LimitID','Limit ID','Limit ID','int',4,null,1,1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 252 and columnid=2
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(252,2,'DepartmentID','Department','Department','int',4,null,1,1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 252 and columnid=3
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(252,3,'interfaceid','Interface','Interface','int',4,null,1,1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 252 and columnid=4
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(252,4,'LimitNo','Limit No','Limit No','varchar',50,null,1,1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 252 and columnid=5
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(252,5,'LowerLimit','Lower Limit','Lower Limit','numeric',9,18,1,1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 252 and columnid=6
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(252,6,'UpperLimit','Upper Limit','Upper Limit','numeric',9,18,1,1,newid())
END
go
-----------------------------------------------------------------------
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM aInterface
WHERE InterfaceID = 92036
IF @intCount = 0
BEGIN
insert into aInterface values(92036,'Approval Level Limits','hqadm',0,1,null,newid(),null)
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM aTables
WHERE TableID = 253
IF @intCount = 0
BEGIN
INSERT INTO aTables VALUES(253,'aApprovalLevelLimits','Approval Level Limits','Approval Level Limits',1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 253 and columnid=1
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(253,1,'DepartmentID','DepartmentID','DepartmentID','int',4,null,1,1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 253 and columnid=2
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(253,2,'interfaceid','interfaceid','interfaceid','int',4,null,1,1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 253 and columnid=3
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(253,3,'LimitId','LimitId','LimitId','int',4,null,1,1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 253 and columnid=4
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(253,4,'DepartmentID','Department','Department','int',4,null,1,1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 253 and columnid=5
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(253,5,'interfaceid','Interface','Interface','int',4,null,1,1,newid())
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM atablecolumns
WHERE TableID = 253 and columnid=5
IF @intCount = 0
BEGIN
INSERT INTO atablecolumns values(253,6,'LimitId','Limit Range','Limit Range','varchar',50,null,1,1,newid())
END
go
------------------------------------------------------------------
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM aInterface
WHERE InterfaceID = 92037
IF @intCount = 0
BEGIN
insert into aInterface values(92037,'Approval','hqadm',0,1,null,newid(),null)
END
go

--delete from     ausergrouprights where interfaceid=92037
---select * from ausergrouprights where interfaceid=92037--- 'RB'
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM aapprovalinterfaces
WHERE interfaceID = 2001
IF @intCount = 0
BEGIN
insert into aapprovalinterfaces values (2001,'HQ Purchase Order')
END
GO
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM aapprovalinterfaces
WHERE interfaceID = 5005
IF @intCount = 0
BEGIN
insert into aapprovalinterfaces values (5005,'Accounts Payments')
END
GO
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM aapprovalinterfaces
WHERE interfaceID = 2000
IF @intCount = 0
BEGIN
insert into aapprovalinterfaces values (2000,'HQ Purchase Request To Vendor')
END
GO
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM aapprovalinterfaces
WHERE interfaceID = 2514
IF @intCount = 0
BEGIN
insert into aapprovalinterfaces values (2514,'HQ Pre-Purchase Order')
END

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='aapprovaltransactions' AND COLUMN_NAME='Active' ) 
Begin
	alter table aapprovaltransactions add Active BIT default(0) with values
end  
go
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='aPackageSettings' AND COLUMN_NAME='ActivateServiceResourceScheduling' ) 
Begin

alter table aPackageSettings add ActivateServiceResourceScheduling bit
end

GO
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='aPackageSettings' AND COLUMN_NAME='CommonVendorForAllPQ' ) 
Begin

alter table apackagesettings add CommonVendorForAllPQ bit

end
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[loPrePurchaseOrderOthCharge]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[loPrePurchaseOrderOthCharge](
	[POorderID] [int] NOT NULL,
	[POOCdetailID] [int] NOT NULL,
	[POAccID] [int] NOT NULL,
	[PODescription] [varchar](100) NULL,
	[POAmount] [numeric](18, 2) NULL
) ON [PRIMARY]
END

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM aReports
WHERE ReportID = 7197
IF @intCount = 0
BEGIN
insert into aReports values (7197,'Pre-PO VendorWise','prepurOrVWise',1,3,null,1)
END
go
DECLARE @intCount INT
SELECT @intCount = count(1) 
FROM ainterface
WHERE interfaceid = 92039
IF @intCount = 0
BEGIN
insert into ainterface values (92039,'Approval Level Hierarchy','hqadm',0,1,NULL,newid(),NULL)
END
Go

Go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Wings requirement(Task-8)
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='Flights' AND COLUMN_NAME='AirlinesName' ) 
BEGIN

alter table Flights add AirlinesName varchar(200)

END

go

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='Flights' AND COLUMN_NAME='TypeofCatering' ) 
BEGIN

alter table Flights add TypeofCatering int

END

go

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='Flights' AND COLUMN_NAME='ExpectedNumberOfPassangers' ) 
BEGIN

alter table Flights add ExpectedNumberOfPassangers int

END

go

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='Flights' AND COLUMN_NAME='DelayDuration' ) 
BEGIN

alter table Flights add DelayDuration numeric(18,2)

END

go

IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='Flights' AND COLUMN_NAME='userid' ) 
BEGIN

alter table Flights add userid int

END



Go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Received From Bijesh on 25.09.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

use [adminv2]
go

if NOT Exists(SELECT 1 FROM areports  WHERE ReportID = 7189)
BEGIN
	INSERT INTO areports VALUES(7189,'Daily Sales Report GST Separately','sale9GST',1,2,NULL,1)
END
GO

if NOT Exists(SELECT 1 FROM areports  WHERE ReportID = 7188)
BEGIN
	INSERT INTO areports VALUES(7188,'Daily Sales and Returns GST Separately','DalSalRetGST',1,2,NULL,1)
END
GO

if NOT Exists(SELECT 1 FROM areports  WHERE ReportID = 7191)
BEGIN
	INSERT INTO areports VALUES(7191,'Sales and Collection Summary GST Separately','sale10GST',1,2,NULL,1)
END
GO

if NOT Exists(SELECT 1 FROM areports  WHERE ReportID = 7193)
BEGIN
	INSERT INTO areports VALUES(7193,'Analysis of Sales by Item GST Separately','sale7GST',1,2,NULL,1)
END
GO

if NOT Exists(SELECT 1 FROM areports  WHERE ReportID = 7194)
BEGIN
	INSERT INTO areports VALUES(7194,'Sales and Collection Detailed With GST Seperatly','SalColDetGstSep',1,2,NULL,1)
END
GO

if NOT Exists(SELECT 1 FROM areports  WHERE ReportID = 7195)
BEGIN
	INSERT INTO areports VALUES(7195,'Sales/Import Analysis With GST Seperatly (Advanced)','SalesImpAdvGstSep',1,2,NULL,1)
END
GO

Go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Wings Update on 25/09/2012 from AADYAKUMAR.D.V
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[LosCashDrawerOpen]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[LosCashDrawerOpen](
	[OpenId] [int] IDENTITY(1,1) NOT NULL,
	[UserId] [int] NOT NULL,
	[OpenedTime] [datetime] NULL,
	[OpenedMode] [char](2) NULL,
	[OpenType] [varchar](20) NULL,
	[ShopId] [int] NOT NULL,
 CONSTRAINT [PK_LosCashDrawerOpen] PRIMARY KEY CLUSTERED 
(
	[OpenId] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_LosCashDrawerOpen_LOUsers]') AND parent_object_id = OBJECT_ID(N'[dbo].[LosCashDrawerOpen]'))
ALTER TABLE [dbo].[LosCashDrawerOpen]  WITH CHECK ADD  CONSTRAINT [FK_LosCashDrawerOpen_LOUsers] FOREIGN KEY([UserId])
REFERENCES [dbo].[LOUsers] ([UserID])


Go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Wings Update on 25/09/2012 from AADYAKUMAR.D.V
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

if NOT Exists(SELECT 1 FROM areports  WHERE ReportID = 7200)
BEGIN

insert into areports 
(ReportID,ReportName,Reportconst,ReportCatId,ReportDetailId,
repModuleCode,ReportActive) values (7200,'Cash 
Drawer','CashDrawer',3,6,'F&B',1)

END
GO

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

USE [adminv2]
GO

/****** Object:  Table [dbo].[tmpSELECTEDPR]    Script Date: 09/25/2012 17:27:10 ******/
IF not EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tmpSELECTEDPR]') AND type in (N'U'))
begin

/****** Object:  Table [dbo].[tmpSELECTEDPR]    Script Date: 09/25/2012 17:27:10 ******/


CREATE TABLE [dbo].[tmpSELECTEDPR](
	[spId] [int] NULL,
	[PRID] [int] NULL
) ON [PRIMARY]


end

Go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Update Description(Wings Requirements Delayed Flight Shedule)on 25/09/2012 from AADYAKUMAR.D.V
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='Flights' AND COLUMN_NAME='DelayDuration' ) 
BEGIN
alter table Flights alter column DelayDuration datetime

end

go

go

IF not  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='Flights' AND COLUMN_NAME='VoucherAmount' ) 
BEGIN

alter table Flights add VoucherAmount numeric(18,8)

end


Go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
if NOT Exists(SELECT 1 FROM areports  WHERE ReportID = 7196)
BEGIN
insert into areports values 
(7196,'Purchase Request Status','PRStatus',1,3,'P&C',1)

end

Go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Alter precesion query given by bijesh on 05.10.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
GO
IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='loslocalpurchaseDetail' AND COLUMN_NAME='lpdPOQuantity' ) 
BEGIN

alter table loslocalpurchaseDetail alter  COLUMN   lpdPOQuantity numeric(18,8)

end

go
GO

IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='loslocalpurchaseDetail' AND COLUMN_NAME='lpdPOUnitPrice' ) 
BEGIN
alter table loslocalpurchaseDetail alter  COLUMN   lpdPOUnitPrice numeric(18,8)
end

go
GO

IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='loslocalpurchaseDetail' AND COLUMN_NAME='lpdItemQuantity' ) 
BEGIN
alter table loslocalpurchaseDetail alter  COLUMN   lpdItemQuantity numeric(18,8)
end

go
GO
IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='loslocalpurchaseDetail' AND COLUMN_NAME='lpdItemUnitPrice' ) 
BEGIN

alter table loslocalpurchaseDetail alter  COLUMN   lpdItemUnitPrice numeric(18,8)

end
go
GO
IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='loslocalpurchaseDetail' AND COLUMN_NAME='lpdItemActualAmount' ) 
BEGIN
alter table loslocalpurchaseDetail alter  COLUMN   lpdItemActualAmount numeric(18,8)

end

go
GO
IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='loslocalpurchaseDetail' AND COLUMN_NAME='lpdItemTaxAmount' ) 
BEGIN
alter table loslocalpurchaseDetail alter  COLUMN   lpdItemTaxAmount numeric(18,8)
end
go

Go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Missing column for inventory active directory login
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF not  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='LOiSettings' AND COLUMN_NAME='InventoryActiveDirectoryLogin' ) 
BEGIN

alter table LOiSettings add  InventoryActiveDirectoryLogin bit

end


Go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:SheeshA Update send to rahul on 9.10.2012 from Benzi
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

GO
IF not EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='apackagesettings' AND COLUMN_NAME='ServiceScheduleType' ) 
BEGIN

alter table apackagesettings add ServiceScheduleType int default 0 with values

End

Go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:XLW-768367
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
GO
IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='losInvoiceHeader' AND COLUMN_NAME='ihdiscount' ) 
BEGIN
alter table losInvoiceHeader alter column ihdiscount numeric(18,8)
End

Go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:KTP-379378
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
GO
IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='losWarrentyClaimHeader' AND COLUMN_NAME='wchCustomerName' ) 
BEGIN
alter table losWarrentyClaimHeader alter column wchCustomerName varchar(500)
End
go

GO
IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='losWarrentyClaimHeader' AND COLUMN_NAME='wchCustomerAddress' ) 
BEGIN
alter table losWarrentyClaimHeader alter column wchCustomerAddress varchar(500)

End
go

Go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:BWH-828932
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
GO
IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='losWarrentyClaimDetail' AND COLUMN_NAME='wcdPQty' ) 
BEGIN
alter table losWarrentyClaimDetail alter column wcdPQty numeric (18,3)
End

go

GO
GO
IF  EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_NAME='losWarrentyClaimDetail' AND COLUMN_NAME='wcdQty' ) 
BEGIN

alter table losWarrentyClaimDetail alter column wcdQty numeric (18,3)

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



--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--FINDTRIGGER
--TRIGGER CREATIONS AND ALTERATIONS

--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
Use adminv2
Go
IF EXISTS (SELECT name From sysobjects WHERE name = 'MagnoliaApproval_Mail' AND type = 'TR')
BEGIN
    DROP TRIGGER MagnoliaApproval_Mail
END
GO 
/*
Created By : Shine Das
Created On : 16.06.2012
Pupose	   : To send the status to the PO/PR creator.
---------------------------------------------------------
Created By : Shine Das
Created On : 19.07.2012
Pupose	   : Added Approval pending details along with message.
----------------------------------------------------------
Ref No 1
Modified By: Shine Das
Modified On: 20.08.2012
Pupose	   : Wataniya need to send approal alert to the very next level only. Currently it sends to all levels
in that range. Need to Handle it.
----------------------------------------------------------

*************************************
INTERFACES USED IN THIS TRIGGER ARE
2000 ----Purchase Request
2001 ----Purchase Order
2514 ----Pre-Purchase Order
8033 ----Goods Request From Godown 
*************************************
*/
      
CREATE Trigger MagnoliaApproval_Mail
On aApprovalStatus after INSERT
As
BEGIN		---Trigger


--EMail Content...
DECLARE @userID INT
DECLARE @POID INT
DECLARE @InterfaceID INT
DECLARE @ApprovedStatus BIT
DECLARE @ApprovalLevel INT
DECLARE @ApprovalLevelName VARCHAR(50)
DECLARE @mailTitle VARCHAR(200)
DECLARE @ApproveStatusDesc VARCHAR(50)
DECLARE @PONO VARCHAR(50)
DECLARE @Mail_Msg VARCHAR(8000)
DECLARE @Email VARCHAR(80)
DECLARE @ApprovalAmount Numeric(18,2)
DECLARE @CurrentTransType VARCHAR(3)
DECLARE @PRuserID INT
DECLARE @PRuserName VARCHAR(50)
DECLARE @RejectReason VARCHAR(200)
DECLARE @RejectReasonHTML VARCHAR(200)
DECLARE @TempCount INT
DECLARE @intFlag INT
DECLARE @ApproveduserID INT
DECLARE @ApproveduserEmail VARCHAR(200)
DECLARE @ApprovedLevelName VARCHAR(200)
DECLARE @ApprovalAwaitingDetails VARCHAR(200)
DECLARE @ApprovalPendingAlterts VARCHAR(200)
DECLARE @CurrentLevelNo INT
DECLARE @NextLevelNo INT
DECLARE @NextLevelID INT
DECLARE @GodownID INT

SET @RejectReasonHTML=''
SET @RejectReason=''
SET @Mail_Msg=''
SET @ApproveduserEmail=''
SET @ApprovedLevelName=''
SET @ApprovalAwaitingDetails =''

DECLARE @PRDeptID INT
DECLARE @emailid VARCHAR(200)
DECLARE @DeptName VARCHAR(200)

SET @emailid =''
SET @DeptName =''


	SELECT @POID = transactionid, @InterfaceID =interfaceid, @ApprovalLevel = ApprovalStatusLevel
	,@ApprovedStatus=Rejected, @userID=userid, @RejectReason=RejectedReason,@PRDeptID=DepartmentID,@GodownID=GodownID From inserted
	
	SET @ApproveduserID=@userID
	
	SELECT @ApproveduserEmail=EmailID From ausers WHERE USERID=@ApproveduserID
	SELECT @ApprovedLevelName=LevelName From aapprovallevelmaster WHERE interfaceid=@InterfaceID
	AND LevelID=@ApprovalLevel 
	
		

	If @InterfaceID=2000 ----PR
		BEGIN
			SET @CurrentTransType='R'
		END
	ELSE IF @InterfaceID=2001  -----PO
		BEGIN
			SET @CurrentTransType='P'
		END 
	ELSE IF @InterfaceID=2514  -----PO
		BEGIN
			SET @CurrentTransType='PP'
		END 
		
 
	IF  @InterfaceID=2001 OR  @InterfaceID=2000 
		BEGIN
		SELECT @PRuserID=pohuserid From loPurchaseOrderHeader WHERE pohpoid=@POID and pohtype=@CurrentTransType
		END
	ELSE IF @InterfaceID=2514  ---- 
		BEGIN
			SELECT @PRuserID=pohuserid From loPrePurchaseOrderHeader WHERE pohpoid=@POID 
		END
	ELSE IF @InterfaceID=8033
		BEGIN
			SELECT @PRuserID=GRHRecAddUserId From MeiGodownRequestHeader WHERE GRHRequestId=@POID 
			SELECT @Email=emailid, @PRuserName=UserName From lousers WHERE userid= @PRuserID and godownid=@GodownID
		SET @Mail_Msg= N'<H4><I>Dear '  + CAST(@PRuserName as VARCHAR(15)) + ',</H4> </I> <PR>'  
		END


   
	IF @InterfaceID = 2000 
	BEGIN
		SELECT @PONO=pohpono, @ApprovalAmount=pohvalue From lopurchaseorderheader WHERE pohType='R' and 
		pohpoid=@POID
		
		SET @Mail_Msg= @Mail_Msg + 'Following Purchase Request has been '	
		SET @mailTitle = 'Purchase Request'
	END
		
	IF @InterfaceID = 2001 
	BEGIN
		SELECT @PONO=pohpono, @ApprovalAmount=pohvalue From lopurchaseorderheader WHERE pohType='P' and 
		pohpoid=@POID
		
		SET @Mail_Msg= @Mail_Msg + 'Following Purchase Order has been '	
		SET @mailTitle = 'Purchase Order'
	END
		
	IF @InterfaceID = 2514 
	BEGIN
		SELECT @PONO=pohpono, @ApprovalAmount=pohvalue From loPrePurchaseOrderHeader WHERE  pohpoid=@POID
		
		SET @Mail_Msg= @Mail_Msg + 'Following Pre-Purchase Order has been '	
		SET @mailTitle = 'Pre-Purchase Order'
	END

	IF @InterfaceID = 8033 
		BEGIN
			SELECT 
				@PONO=a.GRHRequestNo,@ApprovalAmount=sum(b.GRDCostPrice*GRDReqQty) 
				From 
				MeiGodownRequestHeader a  inner join MeiGodownRequestDetail b 
				ON a.GRHRequestId = b.GRDRequestId and a.GRHGodownId =b.GRDGodownId 
				WHERE
				a.GRHRequestId=@POID 
				group by a.GRHRequestNo 		 
				
				SET @Mail_Msg= @Mail_Msg + 'Following Goods Request has been '	
				SET @mailTitle = 'Goods Request From Godown'
		END


		SELECT @ApprovalLevelName=LevelName From aapprovallevelmaster WHERE levelId= @ApprovalLevel

		SET @ApproveStatusDesc=''
		
		If @ApprovedStatus=0
			BEGIN
				SET	@ApproveStatusDesc= ' Approved By '
			END
		If @ApprovedStatus=1
			BEGIN
				SET @ApproveStatusDesc= ' Rejected By '
			END

		SET @Mail_Msg = @Mail_Msg +@ApproveStatusDesc + @ApprovalLevelName + '.'
		SET @ApprovalPendingAlterts=''
		SET @ApprovalPendingAlterts=@ApproveStatusDesc + @ApprovalLevelName 


-------->
	IF @ApprovedStatus=0
	 BEGIN
			CREATE TABLE Temp (LEVELID INT, LEVELNAME VARCHAR(100))
			INSERT INTO Temp
			SELECT a.levelID,a.Levelname From aapprovallevelmaster a inner join aapprovallevellimits b ON a.levelid=b.levelid
			and a.interfaceid=b.interfaceid and a.departmentid=b.departmentid inner join aapprovallimitmaster c ON c.limitid=b.limitid
			and c.interfaceid=b.interfaceid and c.departmentid=b.departmentid WHERE @ApprovalAmount<= c.upperlimit and @ApprovalAmount>=c.lowerlimit
			and c.interfaceid=@InterfaceID and a.levelid not in (SELECT approvalstatuslevel From aapprovalstatus WHERE interfaceid=@InterfaceID and 
			transactionid=@POID)

			SET @intFlag = 1
			SELECT @TempCount=COUNT(*) From Temp
				IF @TempCount>0 
					BEGIN
						SET @Mail_Msg = @Mail_Msg + ' And awaiting approval From '
						SET @ApprovalAwaitingDetails = ' Awaiting approval From '
						WHILE (@intFlag <=@TempCount)
							BEGIN
								SELECT TOP 1 LEVELNAME From Temp
								SET @Mail_Msg = @Mail_Msg + (SELECT TOP 1 LEVELNAME From Temp) + ', '
								SET @ApprovalAwaitingDetails = @ApprovalAwaitingDetails + (SELECT TOP 1 LEVELNAME From Temp) + ', '
								SET @intFlag = @intFlag + 1
								 
								DELETE From Temp WHERE LEVELID=(SELECT TOP 1 LEVELID From temp)
							END
							 
							SET @Mail_Msg=SUBSTRING(@Mail_Msg, 1, LEN(@Mail_Msg)-1) 
							SET @ApprovalAwaitingDetails=SUBSTRING(@ApprovalAwaitingDetails, 1, LEN(@ApprovalAwaitingDetails)-1) 
							SET @Mail_Msg = @Mail_Msg + ' .'
							 
					END
			DROP TABLE Temp
	END
 ------------>

IF @RejectReason<>''
	BEGIN
		SET @RejectReasonHTML = '<TR><TR><TR> <th width=250 align=left> Remarks </th> <th>:</th><th>' + cast(@RejectReason as VARCHAR (500)) + '</th>' 
	END
		

SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
    N'<TR><tr><th width=250 align=left><H4>' + cast('Request' as VARCHAR(50)) + ' No' + '</H4></th>
    <th>:</th><th align=left>' + cast(@PONO as VARCHAR(50)) + '</th>' + 
    N'<tr><th  width=250 align=left><H4> Amount </th><th>:</th><th align=left>' 
    + cast(@ApprovalAmount as VARCHAR(50))  + '</H4></th>'
	+ Cast(@RejectReasonHTML as VARCHAR(200))

SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert </TR></TR>'

SET @mailTitle = 'Fi-es Mail Alert : ' + @mailTitle +  @ApproveStatusDesc + @ApprovalLevelName
 
If @Email<>'' 
	BEGIN
		EXEC msdb.dbo.sp_send_dbmail
			@recipients=@Email,
			@subject= @mailTitle, 
			@body_format = 'HTML',
			@body =@Mail_Msg
	END
	/*Goods Request From Godown - AKNOWLEDGEMENT*/
	
			SET @Mail_Msg= N'<H4><I>Dear '  + CAST(@ApprovedLevelName as VARCHAR(200)) + ',</H4> </I> <PR>' 	
		
			If @ApprovedStatus=0
				BEGIN
					SET @mailTitle = 'Fi-es Mail Alert : Goods Request Approved - Aknowledgement'
					SET @Mail_Msg= @Mail_Msg + 'This is an Aknowledgement for the Approval you have made'
				END 
			If @ApprovedStatus=1
				BEGIN
					SET @mailTitle = 'Fi-es Mail Alert : Goods Request Rejected - Aknowledgement'
					SET @Mail_Msg= @Mail_Msg + 'This is an Aknowledgement for the Reject you have made'
				END
			
			SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
				N'<TR><tr><th width=250 align=left><H4>' + cast('Request' as VARCHAR(50)) + ' No' + '</H4></th>
				<th>:</th><th align=left>' + cast(@PONO as VARCHAR(50)) + '</th>' + 
				N'<tr><th  width=250 align=left><H4> Amount </th><th>:</th><th align=left>' 
				+ cast(@ApprovalAmount as VARCHAR(50))  + '</H4></th>'
				+ Cast(@RejectReasonHTML as VARCHAR(200))

		SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert  </TR></TR>'

		
		If @ApproveduserEmail<>'' 
			BEGIN
				EXEC msdb.dbo.sp_send_dbmail
					@recipients=@ApproveduserEmail,
					@subject= @mailTitle, 
					@body_format = 'HTML',
					@body =@Mail_Msg
			END
			
	----- Ref No 1
		---------------------Start  @NextLevelID
		SELECT @CurrentLevelNo=LevelNo From aapprovallevelmaster WHERE levelid=@ApprovalLevel and interfaceid=@InterfaceID and departmentid = @PRDeptID 
		SET @NextLevelID=0
		 
		SELECT top 1 @NextLevelID = a.levelid From aapprovallevelmaster a inner join aApprovalLevelLimits b ON a.DepartmentID =b.DepartmentID 
			and a.InterfaceID = b.interfaceid and a.LevelID =b.LevelId inner join aApprovalLimitMaster c ON c.DepartmentID =b.DepartmentID 
			and c.interfaceid = b.interfaceid and c.LimitID =b.LimitId  WHERE @ApprovalAmount between c.LowerLimit and c.UpperLimit and c.interfaceid =@InterfaceID 
			and c.departmentid=@PRDeptID and a.levelno < @CurrentLevelNo order by LevelNo desc

		 
		
		IF @NextLevelID<>0
		BEGIN
			SELECT @PRuserName=e.username, @emailid= emailid From aapprovallevelmaster a inner join aapprovallevellimits b
				 ON a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c ON c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d ON d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e ON e.usergroupid=d.usergroupid				 
				 WHERE 
				 @ApprovalAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID 
				 and c.interfaceid=8033 and a.levelid=@NextLevelID  
				 group by e.username,emailid 
				 
				 SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as VARCHAR(50)) + ',</H4> <PR>'  
						If @ApprovedStatus=0
							BEGIN
							SET @Mail_Msg = @Mail_Msg + N'<P>Following Goods Request ' +
							CAST(@ApprovalPendingAlterts as VARCHAR(100)) +'. And awaiting approval From you.'
							END
						If @ApprovedStatus=1
							BEGIN
							SET @Mail_Msg = @Mail_Msg + N'<P>Following Goods Request is' + 
							CAST(@ApprovalPendingAlterts as VARCHAR(100)) + '.'
							END
						
								SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
									N'<TR><tr><th width=250 align=left><H4>' + cast('Request' as VARCHAR(50)) + ' No' + '</H4></th>
									<th>:</th><th align=left>' + cast(@PONO as VARCHAR(50)) + '</th>' + 
									N'<tr><th  width=250 align=left><H4> Amount </th><th>:</th><th align=left>' 
									+ cast(@ApprovalAmount as VARCHAR(50))  + '</H4></th>'
									+ Cast(@RejectReasonHTML as VARCHAR(200))

													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert  </TR></TR> '			
						
						If @emailid<>'' 
							BEGIN
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							END			 
		END
		
		---------------------END 	
		
	--------------------------------------------------------------------------------
	
IF @CurrentTransType='R'
	BEGIN
 
		SET @Mail_Msg= N'<H4><I>Dear '  + CAST(@ApprovedLevelName as VARCHAR(200)) + ',</H4> </I> <PR>' 	
		
	     If @ApprovedStatus=0
		BEGIN
			SET @mailTitle = 'Fi-es Mail Alert : Purchase Request Approved - Aknowledgement'
			SET @Mail_Msg= @Mail_Msg + 'This is an Aknowledgement for the Approval you have made'
		END 
		If @ApprovedStatus=1
		BEGIN
			SET @mailTitle = 'Fi-es Mail Alert : Purchase Request Rejected - Aknowledgement'
			SET @Mail_Msg= @Mail_Msg + 'This is an Aknowledgement for the Reject you have made'
		END
			
		SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
			N'<TR><tr><th width=250 align=left><H4>' + cast('Request' as VARCHAR(50)) + ' No' + '</H4></th>
			<th>:</th><th align=left>' + cast(@PONO as VARCHAR(50)) + '</th>' + 
			N'<tr><th  width=250 align=left><H4> Amount </th><th>:</th><th align=left>' 
			+ cast(@ApprovalAmount as VARCHAR(50))  + '</H4></th>'
			+ Cast(@RejectReasonHTML as VARCHAR(200))

		SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert  </TR></TR>'

		
		If @ApproveduserEmail<>'' 
			BEGIN
				EXEC msdb.dbo.sp_send_dbmail
					@recipients=@ApproveduserEmail,
					@subject= @mailTitle, 
					@body_format = 'HTML',
					@body =@Mail_Msg
			END
			
			
		----- Ref No 1
		---------------------Start  @NextLevelID
		SELECT @CurrentLevelNo=LevelNo From aapprovallevelmaster WHERE levelid=@ApprovalLevel and interfaceid=@InterfaceID and departmentid = @PRDeptID 
		SET @NextLevelID=0
		 
		SELECT top 1 @NextLevelID = a.levelid From aapprovallevelmaster a inner join aApprovalLevelLimits b ON a.DepartmentID =b.DepartmentID 
			and a.InterfaceID = b.interfaceid and a.LevelID =b.LevelId inner join aApprovalLimitMaster c ON c.DepartmentID =b.DepartmentID 
			and c.interfaceid = b.interfaceid and c.LimitID =b.LimitId  WHERE @ApprovalAmount between c.LowerLimit and c.UpperLimit and c.interfaceid =@InterfaceID 
			and c.departmentid=@PRDeptID and a.levelno < @CurrentLevelNo order by LevelNo desc

		 
		
		IF @NextLevelID<>0
		BEGIN
			SELECT @PRuserName=e.username, @emailid= emailid From aapprovallevelmaster a inner join aapprovallevellimits b
				 ON a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c ON c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d ON d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e ON e.usergroupid=d.usergroupid				 
				 WHERE 
				 @ApprovalAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID 
				 and c.interfaceid=2000 and a.levelid=@NextLevelID  
				 group by e.username,emailid 
				 
				 SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as VARCHAR(50)) + ',</H4> <PR>'  
						If @ApprovedStatus=0
							BEGIN
							SET @Mail_Msg = @Mail_Msg + N'<P>Following Purchase Request ' +
							CAST(@ApprovalPendingAlterts as VARCHAR(100)) +'. And awaiting approval From you.'
							END
						If @ApprovedStatus=1
							BEGIN
							SET @Mail_Msg = @Mail_Msg + N'<P>Following Purchase Request is' + 
							CAST(@ApprovalPendingAlterts as VARCHAR(100)) + '.'
							END
						
								SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
									N'<TR><tr><th width=250 align=left><H4>' + cast('Request' as VARCHAR(50)) + ' No' + '</H4></th>
									<th>:</th><th align=left>' + cast(@PONO as VARCHAR(50)) + '</th>' + 
									N'<tr><th  width=250 align=left><H4> Amount </th><th>:</th><th align=left>' 
									+ cast(@ApprovalAmount as VARCHAR(50))  + '</H4></th>'
									+ Cast(@RejectReasonHTML as VARCHAR(200))

													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert  </TR></TR> '			
						
						If @emailid<>'' 
							BEGIN
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							END			 
		END
		
		---------------------END 
		/*
		DECLARE PRCursor CURSOR FOR  ----   Ref No 1 Commented Below.
			 SELECT  e.username,emailid From aapprovallevelmaster a inner join aapprovallevellimits b
				 ON a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c ON c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d ON d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e ON e.usergroupid=d.usergroupid				 
				 WHERE 
				 @ApprovalAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID 
				 and c.interfaceid=2000 and a.levelid<>@ApprovalLevel
				 group by e.username,emailid 

					OPEN PRCursor 
					FETCH NEXT From PRCursor INTO @PRuserName, @emailid

					WHILE @@FETCH_STATUS = 0 
					BEGIN 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as VARCHAR(50)) + ',</H4> <PR>'  
						If @ApprovedStatus=0
							BEGIN
							SET @Mail_Msg = @Mail_Msg + N'<P>Following Purchase Request ' +
							CAST(@ApprovalPendingAlterts as VARCHAR(50)) +'.'
							END
						If @ApprovedStatus=1
							BEGIN
							SET @Mail_Msg = @Mail_Msg + N'<P>Following Purchase Request is' + 
							CAST(@ApprovalPendingAlterts as VARCHAR(50)) + '.'
							END
						
								SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
									N'<TR><tr><th width=250 align=left><H4>' + cast('Request' as VARCHAR(50)) + ' No' + '</H4></th>
									<th>:</th><th align=left>' + cast(@PONO as VARCHAR(50)) + '</th>' + 
									N'<tr><th  width=250 align=left><H4> Amount </th><th>:</th><th align=left>' 
									+ cast(@ApprovalAmount as VARCHAR(50))  + '</H4></th>'
									+ Cast(@RejectReasonHTML as VARCHAR(200))

													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @emailid<>'' 
							BEGIN
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							END			 

					FETCH NEXT From PRCursor INTO @PRuserName, @emailid
					END 
					CLOSE PRCursor 
					DEALLOCATE PRCursor
					*/
		
		 
		
	END
	
	
	IF @CurrentTransType='P'
	BEGIN
 
		SET @Mail_Msg= N'<H4><I>Dear '  + CAST(@ApprovedLevelName as VARCHAR(200)) + ',</H4> </I> <PR>' 	
		
	     If @ApprovedStatus=0
		BEGIN
			SET @mailTitle = 'Fi-es Mail Alert : Purchase Order Approved - Aknowledgement'
			SET @Mail_Msg= @Mail_Msg + 'This is an Aknowledgement for the Approval you have made'
		END 
		If @ApprovedStatus=1
		BEGIN
			SET @mailTitle = 'Fi-es Mail Alert : Purchase Order Rejected - Aknowledgement'
			SET @Mail_Msg= @Mail_Msg + 'This is an Aknowledgement for the Reject you have made'
		END
			
		SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
			N'<TR><tr><th width=250 align=left><H4>' + cast('Purchase Order' as VARCHAR(50)) + ' No' + '</H4></th>
			<th>:</th><th align=left>' + cast(@PONO as VARCHAR(50)) + '</th>' + 
			N'<tr><th  width=250 align=left><H4> Amount </th><th>:</th><th align=left>' 
			+ cast(@ApprovalAmount as VARCHAR(50))  + '</H4></th>'
			+ Cast(@RejectReasonHTML as VARCHAR(200))

		SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert </TR></TR> '

		
		If @ApproveduserEmail<>'' 
			BEGIN
				EXEC msdb.dbo.sp_send_dbmail
					@recipients=@ApproveduserEmail,
					@subject= @mailTitle, 
					@body_format = 'HTML',
					@body =@Mail_Msg
			END
			
			
		
		
		----- Ref No 1
		---------------------Start
	 	SET @NextLevelID=0
		SELECT @CurrentLevelNo=LevelNo From aapprovallevelmaster WHERE levelid=@ApprovalLevel and interfaceid=@InterfaceID and departmentid = @PRDeptID 
		 
		SELECT top 1 @NextLevelID = a.levelid From aapprovallevelmaster a inner join aApprovalLevelLimits b ON a.DepartmentID =b.DepartmentID 
			and a.InterfaceID = b.interfaceid and a.LevelID =b.LevelId inner join aApprovalLimitMaster c ON c.DepartmentID =b.DepartmentID 
			and c.interfaceid = b.interfaceid and c.LimitID =b.LimitId  WHERE @ApprovalAmount between c.LowerLimit and c.UpperLimit and c.interfaceid =@InterfaceID 
			and c.departmentid=@PRDeptID and a.levelno < @CurrentLevelNo order by LevelNo desc
 
		
		IF @NextLevelID<>0
		BEGIN
		SELECT @PRuserName=e.username, @emailid= emailid From aapprovallevelmaster a inner join aapprovallevellimits b
				 ON a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c ON c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d ON d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e ON e.usergroupid=d.usergroupid				 
				 WHERE 
				 @ApprovalAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID 
				 and c.interfaceid=2001 and a.levelid=@NextLevelID   
				 group by e.username,emailid 
				 
				 SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as VARCHAR(50)) + ',</H4> <PR>'  
						If @ApprovedStatus=0
							BEGIN
							SET @Mail_Msg = @Mail_Msg + N'<P>Following Purchase Order ' +
							CAST(@ApprovalPendingAlterts as VARCHAR(100)) +'. And awaiting approval From you.'
							END
						If @ApprovedStatus=1
							BEGIN
							SET @Mail_Msg = @Mail_Msg + N'<P>Following Purchase Order is' + 
							CAST(@ApprovalPendingAlterts as VARCHAR(100)) + '.'
							END
						
								SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
									N'<TR><tr><th width=250 align=left><H4>' + cast('Order' as VARCHAR(50)) + ' No' + '</H4></th>
									<th>:</th><th align=left>' + cast(@PONO as VARCHAR(50)) + '</th>' + 
									N'<tr><th  width=250 align=left><H4> Amount </th><th>:</th><th align=left>' 
									+ cast(@ApprovalAmount as VARCHAR(50))  + '</H4></th>'
									+ Cast(@RejectReasonHTML as VARCHAR(200))

													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert  </TR></TR>'			
						
						If @emailid<>'' 
							BEGIN
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							END			 
		END
		
		---------------------END 
		
		
		
		/*
			DECLARE PRCursor CURSOR FOR
			 SELECT  e.username,emailid From aapprovallevelmaster a inner join aapprovallevellimits b
				 ON a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c ON c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d ON d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e ON e.usergroupid=d.usergroupid				 
				 WHERE 
				 @ApprovalAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID 
				 and c.interfaceid=2000 and a.levelid<>@ApprovalLevel
				 group by e.username,emailid 

					OPEN PRCursor 
					FETCH NEXT From PRCursor INTO @PRuserName, @emailid

					WHILE @@FETCH_STATUS = 0 
					BEGIN 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as VARCHAR(50)) + ',</H4> <PR>'  
						If @ApprovedStatus=0
							BEGIN
							SET @Mail_Msg = @Mail_Msg + N'<P>Following Purchase Order ' +
							CAST(@ApprovalPendingAlterts as VARCHAR(50)) +'.'
							END
						If @ApprovedStatus=1
							BEGIN
							SET @Mail_Msg = @Mail_Msg + N'<P>Following Purchase Order is' + 
							CAST(@ApprovalPendingAlterts as VARCHAR(50)) + '.'
							END
						
								SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
									N'<TR><tr><th width=250 align=left><H4>' + cast('Order' as VARCHAR(50)) + ' No' + '</H4></th>
									<th>:</th><th align=left>' + cast(@PONO as VARCHAR(50)) + '</th>' + 
									N'<tr><th  width=250 align=left><H4> Amount </th><th>:</th><th align=left>' 
									+ cast(@ApprovalAmount as VARCHAR(50))  + '</H4></th>'
									+ Cast(@RejectReasonHTML as VARCHAR(200))

													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @emailid<>'' 
							BEGIN
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							END			 

					FETCH NEXT From PRCursor INTO @PRuserName, @emailid
					END 
					CLOSE PRCursor 
					DEALLOCATE PRCursor
		*/
	END
	
	
	
	
	-------------PP
	
 IF @CurrentTransType='PP'
	BEGIN
 
		SET @Mail_Msg= N'<H4><I>Dear '  + CAST(@ApprovedLevelName as VARCHAR(200)) + ',</H4> </I> <PR>' 	
		
	     If @ApprovedStatus=0
		BEGIN
			SET @mailTitle = 'Fi-es Mail Alert : Pre-Purchase Order Approved - Aknowledgement'
			SET @Mail_Msg= @Mail_Msg + 'This is an Aknowledgement for the Approval you have made'
		END 
		If @ApprovedStatus=1
		BEGIN
			SET @mailTitle = 'Fi-es Mail Alert : Pre-Purchase Order Rejected - Aknowledgement'
			SET @Mail_Msg= @Mail_Msg + 'This is an Aknowledgement for the Reject you have made'
		END
			
		SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
			N'<TR><tr><th width=250 align=left><H4>' + cast('Pre-Purchase Order' as VARCHAR(50)) + ' No' + '</H4></th>
			<th>:</th><th align=left>' + cast(@PONO as VARCHAR(50)) + '</th>' + 
			N'<tr><th  width=250 align=left><H4> Amount </th><th>:</th><th align=left>' 
			+ cast(@ApprovalAmount as VARCHAR(50))  + '</H4></th>'
			+ Cast(@RejectReasonHTML as VARCHAR(200))

		SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert </TR></TR> '

		
		If @ApproveduserEmail<>'' 
			BEGIN
				EXEC msdb.dbo.sp_send_dbmail
					@recipients=@ApproveduserEmail,
					@subject= @mailTitle, 
					@body_format = 'HTML',
					@body =@Mail_Msg
			END
			
			
		
		
		----- Ref No 1
		---------------------Start
		SET @NextLevelID=0
		SELECT @CurrentLevelNo=LevelNo From aapprovallevelmaster WHERE levelid=@ApprovalLevel and interfaceid=@InterfaceID and departmentid = @PRDeptID 
		 
		SELECT top 1 @NextLevelID = a.levelid From aapprovallevelmaster a inner join aApprovalLevelLimits b ON a.DepartmentID =b.DepartmentID 
			and a.InterfaceID = b.interfaceid and a.LevelID =b.LevelId inner join aApprovalLimitMaster c ON c.DepartmentID =b.DepartmentID 
			and c.interfaceid = b.interfaceid and c.LimitID =b.LimitId  WHERE @ApprovalAmount between c.LowerLimit and c.UpperLimit and c.interfaceid =@InterfaceID 
			and c.departmentid=@PRDeptID and a.levelno < @CurrentLevelNo order by LevelNo desc
		
		 
		
		IF @NextLevelID<>0
		BEGIN
		SELECT @PRuserName=e.username, @emailid= emailid From aapprovallevelmaster a inner join aapprovallevellimits b
				 ON a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c ON c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d ON d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e ON e.usergroupid=d.usergroupid				 
				 WHERE 
				 @ApprovalAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID 
				 and c.interfaceid=@InterfaceID and a.levelid=@NextLevelID 
				 group by e.username,emailid 
				 
				 SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as VARCHAR(50)) + ',</H4> <PR>'  
						If @ApprovedStatus=0
							BEGIN
							SET @Mail_Msg = @Mail_Msg + N'<P>Following Pre-Purchase Order ' +
							CAST(@ApprovalPendingAlterts as VARCHAR(100)) +'. And awaiting approval From you.'
							END
						If @ApprovedStatus=1
							BEGIN
							SET @Mail_Msg = @Mail_Msg + N'<P>Following Pre-Purchase Order is' + 
							CAST(@ApprovalPendingAlterts as VARCHAR(100)) + '.'
							END
						
								SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
									N'<TR><tr><th width=250 align=left><H4>' + cast('Pre- Purchase Order' as VARCHAR(50)) + ' No' + '</H4></th>
									<th>:</th><th align=left>' + cast(@PONO as VARCHAR(50)) + '</th>' + 
									N'<tr><th  width=250 align=left><H4> Amount </th><th>:</th><th align=left>' 
									+ cast(@ApprovalAmount as VARCHAR(50))  + '</H4></th>'
									+ Cast(@RejectReasonHTML as VARCHAR(200))

													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert  </TR></TR>'			
						
						If @emailid<>'' 
							BEGIN
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							END			 
		END
		
		---------------------END 
		
 
	END
	
	
	
	 
	
	
	
END		
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
Use adminv2
Go
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'MagnoliaApprovalRollBack_Mail' AND type = 'TR')
BEGIN
    DROP TRIGGER MagnoliaApprovalRollBack_Mail
END
GO 
/*
Created By : Shine Das
Created On : 23.06.2012
Pupose	   : To send Roll Back status to the Respective Persons.
*/
      
CREATE Trigger MagnoliaApprovalRollBack_Mail
On aApprovalRollBackTrans after Insert
As
Begin		---Trigger


--EMail Content...
Declare @userID INT
Declare @POID INT
Declare @InterfaceID INT
Declare @Rejected bit
Declare @ApprovedStatus bit
Declare @ApprovalLevel INT
Declare @ApprovalLevelName Varchar(50)
Declare @mailTitle Varchar(200)
Declare @ApproveStatusDesc Varchar(50)
Declare @PONO Varchar(50)
Declare @Mail_Msg Varchar(8000)
Declare @Emailid Varchar(80)
Declare @ApprovalAmount Numeric(18,2)
Declare @CurrentTransType Varchar(3)
Declare @PRuserID INT
Declare @PRuserName Varchar(50)
Declare @PRollBackuser Varchar(50)
Declare @RejectReason Varchar(200)
Declare @TransDesc Varchar(200)
Declare @RejectReasonHTML Varchar(200)
Declare @PRDeptID INT
Declare @PRDateTime DATETIME   

SET @RejectReasonHTML=''
SET @RejectReason=''
SET @TransDesc=''
set @ApproveStatusDesc=''

select @POID = transactionid, @InterfaceID =interfaceid, @ApprovalLevel = ApprovalStatusLevel
,@ApprovedStatus=Rejected, @userID=userid, @RejectReason=RollBackReason, @PRDeptID=departmentid,
@Rejected=Rejected
from inserted

Select @PRollBackuser=UserName from ausers where userid=@userID

IF @ApprovedStatus=1 
	BEGIN
		SET @ApproveStatusDesc=' Rejection '
	END
ELSE
 BEGIN
	SET @ApproveStatusDesc=' Approval '
 END 

If @InterfaceID=2000 
	Begin
		SET @CurrentTransType='R'
		SET @TransDesc= 'Purchase Request No '
	End
ELSE IF @InterfaceID=2001
	BEGIN
		SET @CurrentTransType='P'
		SET @TransDesc= 'Purchase Order No '
	END 
ELSE IF @InterfaceID=5005
	BEGIN
		SET @CurrentTransType=''
		SET @TransDesc= 'Payment No '
	END 
ELSE IF @InterfaceID=8033
	BEGIN
		SET @CurrentTransType=''
		SET @TransDesc= 'Goods Request No '
	END 
 

--aApprovalRollBackTrans
If @InterfaceID=2000 OR @InterfaceID=2001
	BEGIN 
		select @ApprovalAmount=pohvalue,@PONO=pohpono,@PRDateTime =pohPodate from loPurchaseOrderHeader 
		where pohpoid=@POID and pohtype=@CurrentTransType 
	END
ELSE IF @InterfaceID=5005
	BEGIN
		select @ApprovalAmount=phAmount,@PONO=phPaymentNo, @PRDateTime =phPaymentDate from aHQPaymentVoucherHeader 
		where phPaymentID=@POID and @PRDeptID=phDepartmentID
	END
ELSE IF @InterfaceID=8033
	BEGIN
 		 select @PONO=a.GRHRequestNo,@ApprovalAmount=sum(b.GRDCostPrice*GRDReqQty),@PRDateTime =a.GRHRequestDate 
 		 from MeiGodownRequestHeader a inner join MeiGodownRequestDetail b on a.GRHRequestId = b.GRDRequestId 
 		 and a.GRHGodownId =b.GRDGodownId Where a.GRHRequestId=@POID group by a.GRHRequestNo,a.GRHRequestDate 
	END
 
 
 	Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Approval Rollbacked'
	 
		DECLARE PRCursor CURSOR FOR
			 select  e.username,emailid from aapprovallevelmaster a inner join aapprovallevellimits b
					 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
					inner join aapprovallimitmaster c on c.limitid=b.limitid and 
					c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
					inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
					Inner join ausers e on e.usergroupid=d.usergroupid
				 where 
					@ApprovalAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID
				 group by e.username,emailid 

					OPEN PRCursor 
					FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid

					WHILE @@FETCH_STATUS = 0 
					BEGIN 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>Following' + CAST(@ApproveStatusDesc as VARCHAR(50)) + 'has been Rollbacked...'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4>' + Cast(@TransDesc as varchar(200)) + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Requested Date </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
											+ cast(@ApprovalAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><tr><th  width=250 align=left><H4>Rollback Done By </th><th>:</th><th align=left>' 
											+ cast(@PRollBackuser as varchar(250))  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Rollback Reason </th><th>:</th><th align=left>' 
											+ cast(@RejectReason as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @emailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 

					FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid
					END 
					CLOSE PRCursor 
					DEALLOCATE PRCursor


 
End		
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
Use adminv2
Go
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'MagnoliaGoodsRequestFromGodown_Mail' AND type = 'TR')
BEGIN
    DROP TRIGGER MagnoliaGoodsRequestFromGodown_Mail
END
GO 
/*
Created By : Shine Das
Created On : 01.09.2012
Purpose	   : To send email alerts to the approval levels and aknowledgement to the creator of the transaction.
*/
      
CREATE Trigger MagnoliaGoodsRequestFromGodown_Mail
On MeiGodownRequestHeader after Insert
As
Begin		---Trigger


	--EMail Content...
	Declare @userID INT
	Declare @userCount INT
	Declare @PRGdwnID INT
	Declare @PRDeptID INT
	Declare @POID INT
	Declare @LimitID INT
	Declare @ApprovalLevel INT
	Declare @ApprovalLevelName Varchar(50)
	Declare @mailTitle Varchar(200)
	Declare @PONO Varchar(50)
	Declare @Mail_Msg Varchar(8000)
	Declare @Emailid Varchar(80)
	Declare @PRAmount Numeric(18,2)
	Declare @CurrentTransType Varchar(3)
	Declare @PRuserID INT
	Declare @PRuserName Varchar(50)
	Declare @PRDateTime DATETIME              
	Declare @PRRemarks Varchar(250)
	Declare @GdwnName Varchar(250)
	Declare @PRUserEmailid Varchar(80)
	Declare @DeptName Varchar(50)

 
	SET @DeptName =''
	select @POID = GRHRequestId, @PONO=GRHRequestNo, @PRDateTime =GRHRequestDate, 
		  @PRAmount=GRHTotalCostPrice,@PRuserID=GRHRecAddUserId,@PRGdwnID=GRHGodownId,@PRRemarks=GRHRemarks from inserted
	  
	 
 
	  
		Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Goods Request From Godown Needs Your Approval'
		SELECT @GdwnName= godownname, @PRDeptID=departmentid from agodown where godownid=@PRGdwnID		
		SELECT @DeptName =DepartmentName from  adepartmentmaster where DepartmentID=@PRDeptID
		
 
		select top 1 @PRuserName= a.LevelName,@emailid=emailid from aapprovallevelmaster a inner join aapprovallevellimits b
				 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e on e.usergroupid=d.usergroupid
				 where 
				 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID
				 and b.interfaceid = 8033
				 --group by e.username,emailid 
				 order by LevelNo desc
					 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>Following Goods Request Needs Approval From You...'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4>Goods Request No ' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>From Godown </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@GdwnName,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Date </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @emailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 
							
		
		/* PURCHASE REQUEST AKNOWLEDGEMENT*/			
					SET @mailTitle=''
					SET @PRuserName=''
					SET @Mail_Msg=''
					
					Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Goods Request   -- Aknowledgement'
					
					SELECT @PRuserName=Username,@PRUserEmailid=EmailID from lousers where userid=@PRuserID and GodownID=@PRGdwnID
		 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>This is an aknowledgement for the below Goods Request you have made.'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4> Goods Request No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +		
										     N'<tr><th  width=250 align=left><H4>From Godown </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@GdwnName,103)  + '</H4></th>' +								    
											N'<tr><th  width=250 align=left><H4> Date </th><th>:</th><th align=left>' 											
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @PRUserEmailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@PRUserEmailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 	 
							
 
	
END
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
Use adminv2
Go
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'MagnoliaGoodsRequestFromGodown_UPDATEMail' AND type = 'TR')
BEGIN
    DROP TRIGGER MagnoliaGoodsRequestFromGodown_UPDATEMail
END
GO 
/*
Created By : Shine Das
Created On : 01.09.2012
Purpose	   : To send email alerts to the approval levels and aknowledgement to the creator of the transaction.
*/
      
CREATE Trigger MagnoliaGoodsRequestFromGodown_UPDATEMail
On MeiGodownRequestHeader  after UPDATE
As
Begin		---Trigger


	--EMail Content...
	Declare @userID INT
	Declare @userCount INT
	Declare @PRGdwnID INT
	Declare @PRDeptID INT
	Declare @POID INT
	Declare @LimitID INT
	Declare @ApprovalLevel INT
	Declare @ApprovalLevelName Varchar(50)
	Declare @mailTitle Varchar(200)
	Declare @PONO Varchar(50)
	Declare @Mail_Msg Varchar(8000)
	Declare @Emailid Varchar(80)
	Declare @PRAmount Numeric(18,2)
	Declare @CurrentTransType Varchar(3)
	Declare @PRuserID INT
	Declare @PRuserName Varchar(50)
	Declare @PRDateTime DATETIME              
	Declare @PRRemarks Varchar(250)
	Declare @GdwnName Varchar(250)
	Declare @PRUserEmailid Varchar(80)
	Declare @DeptName Varchar(50)
	 Declare @TRANCONFIRMED BIT
	 Declare @PROLDAmount Numeric(18,2)

 SET @PROLDAmount=0.00
 SET @PRAmount=0.00
	SET @DeptName =''
	select @POID = GRHRequestId, @PONO=GRHRequestNo, @PRDateTime =GRHRequestDate, 
		  @PROLDAmount=GRHTotalCostPrice,@PRuserID=GRHRecAddUserId,@PRGdwnID=GRHGodownId,@PRRemarks=GRHRemarks from deleted
		  
		 
	select @PRAmount=GRHTotalCostPrice from inserted --where grhrequestid=@POID and grhgodownid=@PRGdwnID	  
	 SELECT @TRANCONFIRMED=GRHTransfinished from inserted
	 
	 --select @PRAmount=GRHTotalCostPrice from MeiGodownRequestHeader where grhrequestid=@POID and grhgodownid=@PRGdwnID
 
	 
	IF @PROLDAmount=@PRAmount
		BEGIN
			If @TRANCONFIRMED=1 OR @TRANCONFIRMED=0
			BEGIN
				RETURN
			END 
		END

 
	  
		Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Goods Request From Godown After Edit'
		SELECT @GdwnName= godownname, @PRDeptID=departmentid from agodown where godownid=@PRGdwnID		
		SELECT @DeptName =DepartmentName from  adepartmentmaster where DepartmentID=@PRDeptID
		
 
		select top 1 @PRuserName= a.LevelName,@emailid=emailid from aapprovallevelmaster a inner join aapprovallevellimits b
				 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e on e.usergroupid=d.usergroupid
				 where 
				 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID
				 and b.interfaceid = 8033
				 --group by e.username,emailid 
				 order by LevelNo desc
					 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>Following Goods Request has been edited and needs Approval From You...'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4>Goods Request No ' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>From Godown </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@GdwnName,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Date </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										     N'<tr><th  width=250 align=left><H4>Old Amount </th><th>:</th><th align=left>' 
											+ cast(@PROLDAmount as varchar(50))  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>New Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @emailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 
							
		
		/* PURCHASE REQUEST AKNOWLEDGEMENT*/			
					SET @mailTitle=''
					SET @PRuserName=''
					SET @Mail_Msg=''
					
					Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Goods Request Edited  -- Aknowledgement'
					
					SELECT @PRuserName=Username,@PRUserEmailid=EmailID from lousers where userid=@PRuserID and godownid=@PRGdwnID
		 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>This is an aknowledgement for the below Goods Request you have edited.'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4> Goods Request No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +		
										     N'<tr><th  width=250 align=left><H4>From Godown </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@GdwnName,103)  + '</H4></th>' +								    
											N'<tr><th  width=250 align=left><H4> Date </th><th>:</th><th align=left>' 											
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Old Amount </th><th>:</th><th align=left>' 
											+ cast(@PROLDAmount as varchar(50))  + '</H4></th>' + 
										    N'<tr><th  width=250 align=left><H4>New Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @PRUserEmailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@PRUserEmailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 	 
							
 
	
END
GO



GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
Use adminv2
Go
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'MagnoliaPayments_Mail' AND type = 'TR')
BEGIN
    DROP TRIGGER MagnoliaPayments_Mail
END
GO 
/*
Created By : Shine Das
Created ON : 10.07.2012
Purpose	   : To send the approval required mail to authorised persons.
*/
      
CREATE Trigger MagnoliaPayments_Mail
ON aHQPaymentVoucherHeader after Insert
As
BEGIN		---Trigger


--EMail Content...
DECLARE @userID INT
DECLARE @userCount INT
DECLARE @PDeptID INT
DECLARE @PID INT
DECLARE @LimitID INT
DECLARE @ApprovalLevel INT
DECLARE @ApprovalLevelName VARCHAR(50)
DECLARE @mailTitle VARCHAR(200)
DECLARE @PNO VARCHAR(50)
DECLARE @Mail_Msg VARCHAR(8000)
DECLARE @Emailid VARCHAR(80)
DECLARE @PAmount Numeric(18,2)
DECLARE @CurrentTransType VARCHAR(3)
DECLARE @PuserID INT
DECLARE @PuserName VARCHAR(50)
DECLARE @PDATETIME DATETIME              
DECLARE @PRemarks VARCHAR(250)
DECLARE @NeedApproval BIT
 
 SELECT @NeedApproval=needapproval FROM apackagesettings
 IF @NeedApproval=0 
 BEGIN
	RETURN
 END

SELECT @PID = phPaymentID, @PNO=phPaymentNo, @PDATETIME =phPaymentDate,@PAmount=phAmount, @PuserID=phuserid,
@PDeptID=phDepartmentID,@PRemarks=phRemarks  FROM inserted

 
 
		SET @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PNO as VARCHAR(50)) +' -- Payment Needs Your Approval'
	 
		DECLARE PRCursor CURSOR FOR
			 SELECT  e.username,emailid FROM aapprovallevelmaster a INNER JOIN aapprovallevellimits b
				 ON a.levelid=b.levelid AND a.INTerfaceID=b.INTerfaceid AND a.departmentid = b.departmentid
				 INNER JOIN aapprovallimitmaster c ON c.limitid=b.limitid AND 
				 c.INTerfaceID=b.INTerfaceid AND c.departmentid = b.departmentid
				 INNER JOIN aapprovalusergrouprights d ON d.approvalrights = b.levelid AND d.INTerfaceID=b.INTerfaceid 
				 INNER JOIN ausers e ON e.usergroupid=d.usergroupid
				 WHERE 
				 @PAmount between c.lowerlimit AND c.upperlimit AND a.departmentid =@PDeptID
				 GROUP BY e.username,emailid 

					OPEN PRCursor 
					FETCH NEXT FROM PRCursor INTO @PuserName, @emailid

					WHILE @@FETCH_STATUS = 0 
					BEGIN 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PuserName as VARCHAR(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>Following Payment Needs Approval FROM You...'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4> Payment No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PNO as VARCHAR(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Payment Date </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@PDATETIME,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Payment Amount </th><th>:</th><th align=left>' 
											+ cast(@PAmount as VARCHAR(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRemarks as VARCHAR(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						IF @emailid<>'' 
							BEGIN
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							END			 

					FETCH NEXT FROM PRCursor INTO @PuserName, @emailid
					END 
					CLOSE PRCursor 
					DEALLOCATE PRCursor	
	 
	
END
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
Use adminv2
Go
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'MagnoliaPrePurchaseOrder_Mail' AND type = 'TR')
BEGIN
    DROP TRIGGER MagnoliaPrePurchaseOrder_Mail
END
GO 
/*
Created By : Shine Das
Created On : 12.07.2012
Purpose	   : To send alerts to the respective persons who need to approve Pre-Purchase Order.
*/
      
CREATE Trigger MagnoliaPrePurchaseOrder_Mail
On loPrePurchaseOrderHeader after Insert
As
Begin		---Trigger


	--EMail Content...
	Declare @userID INT
	Declare @userCount INT
	Declare @PRDeptID INT
	Declare @POID INT
	Declare @LimitID INT
	Declare @ApprovalLevel INT
	Declare @ApprovalLevelName Varchar(50)
	Declare @mailTitle Varchar(200)
	Declare @PONO Varchar(50)
	Declare @Mail_Msg Varchar(8000)
	Declare @Emailid Varchar(80)
	Declare @PRAmount Numeric(18,2)
	Declare @CurrentTransType Varchar(3)
	Declare @PRuserID INT
	Declare @PRuserName Varchar(50)
	Declare @PRDateTime DATETIME              
	Declare @PRRemarks Varchar(250)
	Declare @DeptName Varchar(250)
	Declare @PRUserEmailid Varchar(80)

 
	SET @DeptName =''
	select @POID = pohpoid, @PONO=pohpono, @PRDateTime =pohPodate, @CurrentTransType = pohtype, 
		   @PRAmount=pohvalue, @PRuserID=pohuserid,@PRDeptID=pohdepartmentID,@PRRemarks=pohremarks from inserted
	  
		Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' --Pre Purchase Order Needs Your Approval'
		SELECT @DeptName= departmentname from adepartmentmaster where DepartmentID=@PRDeptID
		
		
		select top 1 @PRuserName= a.LevelName,@emailid=emailid from aapprovallevelmaster a inner join aapprovallevellimits b
				 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e on e.usergroupid=d.usergroupid
				 where 
				 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID
				 and b.interfaceid = 2514
				 --group by e.username,emailid 
				 order by LevelNo desc
					 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>Following Pre Purchase Order Needs Approval From You...'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4>Pre Purchase Order' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Date </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @emailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 
							
		
		/* PURCHASE REQUEST AKNOWLEDGEMENT*/			
					SET @mailTitle=''
					SET @PRuserName=''
					SET @Mail_Msg=''
					
					Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Pre Purchase Order -- Aknowledgement'
					
					SELECT @PRuserName=Username,@PRUserEmailid=EmailID from ausers where userid=@PRuserID
		 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>This is an aknowledgement for the below Pre Purchase Order you have made.'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4> Pre Purchase Order No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Pre Purchase Order Date </th><th>:</th><th align=left>' 											
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @PRUserEmailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@PRUserEmailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 	 
							
		
		
		/*
		DECLARE PRCursor CURSOR FOR
			 select  e.username,emailid from aapprovallevelmaster a inner join aapprovallevellimits b
				 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e on e.usergroupid=d.usergroupid
				 where 
				 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID
				 and b.interfaceid = 2514
				 group by e.username,emailid 

					OPEN PRCursor 
					FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid

					WHILE @@FETCH_STATUS = 0 
					BEGIN 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>Following Pre Purchase Order Needs Approval From You...'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4>Pre Purchase Order' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Date </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @emailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 

					FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid
					END 
					CLOSE PRCursor 
					DEALLOCATE PRCursor

				*/ 
	
END
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
Use adminv2
Go
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'MagnoliaPrePurchaseOrder_Update_Mail' AND type = 'TR')
BEGIN
    DROP TRIGGER MagnoliaPrePurchaseOrder_Update_Mail
END
GO 
/*
Created By : Shine Das
Created On : 12.07.2012
Purpose	   : To send alerts to the respective persons who need to approve Pre-Purchase Order.
*/
      
CREATE Trigger MagnoliaPrePurchaseOrder_Update_Mail
On loPrePurchaseOrderHeader after UPDATE
As
Begin		---Trigger


	--EMail Content...
	Declare @userID INT
	Declare @userCount INT
	Declare @PRDeptID INT
	Declare @POID INT
	Declare @LimitID INT
	Declare @ApprovalLevel INT
	Declare @ApprovalLevelName Varchar(50)
	Declare @mailTitle Varchar(200)
	Declare @PONO Varchar(50)
	Declare @Mail_Msg Varchar(8000)
	Declare @Emailid Varchar(80)
	Declare @PRAmount Numeric(18,2)
	Declare @CurrentTransType Varchar(3)
	Declare @PRuserID INT
	Declare @PRuserName Varchar(50)
	Declare @PRDateTime DATETIME              
	Declare @PRRemarks Varchar(250)
    Declare @DeptName Varchar(250)
    Declare @PRCancel BIT
    Declare @PROLDAmount Numeric(18,2)
    Declare @TRANCONFIRMED BIT
    
    Declare @PRUserEmailid Varchar(80)
 
 
 
 
SET @DeptName =''
	select @POID = pohpoid, @PONO=pohpono, @PRDateTime =pohPodate, @CurrentTransType = pohtype, 
		   @PROLDAmount=pohvalue, @PRuserID=pohuserid,@PRDeptID=pohdepartmentID,@PRRemarks=pohremarks,
		   --@PRCancel=pohCancel from deleted 
		   @PRCancel=pohCancel from deleted
		   
		   
		   SELECT @TRANCONFIRMED=pohVerified from inserted
		   
		   	select @PRAmount=pohvalue from loprepurchaseorderheader where pohpoid=@POID  and pohdepartmentid=@PRDeptID 
								and pohtype='PP'  and pohcancel=0
								
IF @PROLDAmount=@PRAmount
BEGIN
	If @TRANCONFIRMED=1 OR @TRANCONFIRMED=0
	BEGIN
		RETURN
	END 
END




	IF @PRCancel=1 
		BEGIN
			Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' --Pre Purchase Order Has Been Deleted..'
		END
	ELSE
		BEGIN
			Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' --Pre Purchase Order Has Been Changed; And Need Your Approval...'
		END 
		
	
	SELECT @DeptName= departmentname from adepartmentmaster where DepartmentID=@PRDeptID
	 
	 
	 
	  select top 1 @PRuserName= a.LEVELNAME,@emailid=emailid from aapprovallevelmaster a inner join aapprovallevellimits b
				 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e on e.usergroupid=d.usergroupid
				 where 
				 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID
				 and b.interfaceid=2514
				 --group by e.username,emailid 
				 order by LevelNo desc

					SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						
						IF @PRCancel=1 
							BEGIN
								Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' Deleted Pre Purchase Order Details..'
							END
						ELSE
							BEGIN
								SET @Mail_Msg = @Mail_Msg + N'<P>Pre Purchase Order Details After Edit......'
							END
		
						--SET @Mail_Msg = @Mail_Msg + N'<P>Pre Purchase Order Details After Edit......'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4>Pre Purchase Order' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Date </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount Before Edit </th><th>:</th><th align=left>' 
											+ cast(@PROLDAmount as varchar(50))  + '</H4></th>' + 
										    N'<tr><th  width=250 align=left><H4>Amount After Edit </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert ' 
						
						If @emailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 



			/* PURCHASE ORDER AKNOWLEDGEMENT*/			
					SET @mailTitle=''
					SET @PRuserName=''
					SET @Mail_Msg=''
					SET @PRUserEmailid=''
					
					Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Purchase Order Has Been Changed -- Aknowledgement'
					
					SELECT @PRuserName=Username,@PRUserEmailid=EmailID from ausers where userid=@PRuserID
		 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>This is an aknowledgement for the below Pre-Purchase Order you have Edited.'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4>Pre-Purchase Order No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Date </th><th>:</th><th align=left>' 											
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount Before Edit </th><th>:</th><th align=left>' 
											+ cast(@PROLDAmount as varchar(50))  + '</H4></th>' + 
										    N'<tr><th  width=250 align=left><H4>Amount After Edit </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert </TR></TR>'			
						
						If @PRUserEmailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@PRUserEmailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End		
							
				 
	 
	 
	 /*
		DECLARE PRCursor CURSOR FOR
			 select  e.username,emailid from aapprovallevelmaster a inner join aapprovallevellimits b
				 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e on e.usergroupid=d.usergroupid
				 where 
				 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID
				 and b.interfaceid=2514
				 group by e.username,emailid 

					OPEN PRCursor 
					FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid

					WHILE @@FETCH_STATUS = 0 
					BEGIN 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						
						IF @PRCancel=1 
							BEGIN
								Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' Deleted Pre Purchase Order Details..'
							END
						ELSE
							BEGIN
								SET @Mail_Msg = @Mail_Msg + N'<P>Pre Purchase Order Details After Edit......'
							END
		
						--SET @Mail_Msg = @Mail_Msg + N'<P>Pre Purchase Order Details After Edit......'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4>Pre Purchase Order' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Date </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @emailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 

					FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid
					END 
					CLOSE PRCursor 
					DEALLOCATE PRCursor
		*/
 
	
END
GO




GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
Use adminv2
Go
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'MagnoliaPurchaseRequest_Update_Mail' AND type = 'TR')
BEGIN
    DROP TRIGGER MagnoliaPurchaseRequest_Update_Mail
END
GO 
/*
Created By : Shine Das
Created On : 22.06.2012
Purpose	   : To send the approval required mail to authorised persons.
<----------------------------------------------------------------------------------------->
Ref No : 1
Modified By		: Shine
Modified On		: 14.08.2012
Purpose			: Wataniya need not to send alert to all of the levels when editing a PR or PO.
It only needs to send alert to the immediate person who need to approve first.   
<--------------------------------------------------------------------------------------------->
*/
      
CREATE Trigger MagnoliaPurchaseRequest_Update_Mail
On lopurchaseorderheader after UPDATE
As
Begin		---Trigger


--EMail Content...
Declare @userID INT
Declare @userCount INT
Declare @PRDeptID INT
Declare @POID INT
Declare @LimitID INT
Declare @ApprovalLevel INT
Declare @ApprovalLevelName Varchar(50)
Declare @mailTitle Varchar(200)
Declare @PONO Varchar(50)
Declare @Mail_Msg Varchar(8000)
Declare @Emailid Varchar(80)
Declare @PRAmount Numeric(18,2)
Declare @CurrentTransType Varchar(3)
Declare @PRuserID INT
Declare @PRuserName Varchar(50)
Declare @PRDateTime DATETIME              
Declare @PRRemarks Varchar(250)
Declare @TRANCANCELLED BIT
Declare @PRUserEmailid Varchar(80)
Declare @DeptName Varchar(80)
Declare @PROLDAmount Numeric(18,2)

Declare @TRANCONFIRMED BIT
Declare @TRANONHOLD BIT

 
SET @DeptName=''
select @POID = pohpoid, @PONO=pohpono, @PRDateTime =pohPodate, @CurrentTransType = pohtype, @TRANCANCELLED=pohcancel,
	   @PROLDAmount=pohvalue, @PRuserID=pohuserid,@PRDeptID=pohdepartmentID,@PRRemarks=pohremarks 
from DELETED 

SELECT @TRANCONFIRMED=pohapproved,@TRANONHOLD=pohpoonhold from inserted

SELECT @DeptName=DepartmentName from adepartmentmaster where departmentid=@PRDeptID

select @PRAmount=pohvalue from lopurchaseorderheader where pohpoid=@POID  and pohdepartmentid=@PRDeptID 
and pohtype=@CurrentTransType  and pohcancel=0

IF @PROLDAmount=@PRAmount 
BEGIN

	If @TRANCONFIRMED=1 OR @TRANCONFIRMED=0
	BEGIN
		RETURN
	END 

	IF @CurrentTransType='P'
	BEGIN
		If @TRANONHOLD=0
			BEGIN
				RETURN
			END 
	END
END



IF @TRANCANCELLED<>1
BEGIN 
	IF @CurrentTransType='R' 	---PR Start
		Begin	 
			Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Purchase Request Has Been Changed; And Need Your Approval...'
		 
			select top 1 @PRuserName=e.username, @emailid=emailid from aapprovallevelmaster a inner join aapprovallevellimits b
					 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
					 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
					 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
					 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
					 Inner join ausers e on e.usergroupid=d.usergroupid
					 where 
					 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID  and c.interfaceid=2000
					 --group by e.username,emailid 
					    order by a.LevelNo desc
						 
---@PRAmount 
							SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
							SET @Mail_Msg = @Mail_Msg + N'<P> Purchase Request Details After Edit...'
								SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
												N'<TR><tr><th width=250 align=left><H4> Purchase Request No' + '</H4></th>
												<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
												N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
												 + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
												N'<tr><th  width=250 align=left><H4>Requested Date </th><th>:</th><th align=left>' 
												+ CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
												N'<tr><th  width=250 align=left><H4>Amount Before Edit </th><th>:</th><th align=left>' 
												+ cast(@PROLDAmount as varchar(50))  + '</H4></th>' + 
												N'<tr><th  width=250 align=left><H4>Amount After Edit </th><th>:</th><th align=left>' 
												+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
												N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
												+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
														
							SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert </TR></TR>'				
							
							If @emailid<>'' 
								Begin
									EXEC msdb.dbo.sp_send_dbmail
										@recipients=@emailid,
										@subject= @mailTitle, 
										@body_format = 'HTML',
										@body =@Mail_Msg
								End			 
			
			
			/*  Ref No : 1  Start
			DECLARE PRCursor CURSOR FOR
				 select  e.username,emailid from aapprovallevelmaster a inner join aapprovallevellimits b
					 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
					 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
					 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
					 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
					 Inner join ausers e on e.usergroupid=d.usergroupid
					 where 
					 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID  and c.interfaceid=2000
					 group by e.username,emailid 

						OPEN PRCursor 
						FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid

						WHILE @@FETCH_STATUS = 0 
						BEGIN 
							SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
							SET @Mail_Msg = @Mail_Msg + N'<P> Purchase Request Details After Edit...'
								SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
												N'<TR><tr><th width=250 align=left><H4> Purchase Request No' + '</H4></th>
												<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
												N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
												 + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
												N'<tr><th  width=250 align=left><H4>Requested Date </th><th>:</th><th align=left>' 
												+ CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
												N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
												+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
												N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
												+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
														
							SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
							
							If @emailid<>'' 
								Begin
									EXEC msdb.dbo.sp_send_dbmail
										@recipients=@emailid,
										@subject= @mailTitle, 
										@body_format = 'HTML',
										@body =@Mail_Msg
								End			 

			FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid
			END 
			CLOSE PRCursor 			
			DEALLOCATE PRCursor
			Ref No : 1 End   */  
			
						
			/* PURCHASE REQUEST AKNOWLEDGEMENT*/			
					SET @mailTitle=''
					SET @PRuserName=''
					SET @Mail_Msg=''
					SET @PRUserEmailid=''
					
					Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Purchase Request Has Been Changed -- Aknowledgement'
					
					SELECT @PRuserName=Username,@PRUserEmailid=EmailID from ausers where userid=@PRuserID
		 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>This is an aknowledgement for the below Purchase Request you have edited.'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4> Purchase Request No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Requested Date </th><th>:</th><th align=left>' 											
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount Before Edit </th><th>:</th><th align=left>' 
											+ cast(@PROLDAmount as varchar(50))  + '</H4></th>' + 
										    N'<tr><th  width=250 align=left><H4>Amount After Edit </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert </TR></TR>'	 		
						
						If @PRUserEmailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@PRUserEmailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 
							
						

		End	---PR END	
		
		
		IF @CurrentTransType='P' 	---PR Start
		Begin	 
			Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Purchase Order Has Been Changed; And Need Your Approval...'
		 
			
			select top 1 @PRuserName=e.username, @emailid=emailid from aapprovallevelmaster a inner join aapprovallevellimits b
					 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
					 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
					 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
					 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
					 Inner join ausers e on e.usergroupid=d.usergroupid
					 where 
					 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID  and c.interfaceid=2001
					 --group by e.username,emailid 
					 order by a.LevelNo desc

 
							SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
							SET @Mail_Msg = @Mail_Msg + N'<P>Purchase Order Details After Edit.....'
								SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
												N'<TR><tr><th width=250 align=left><H4> Purchase Order No' + '</H4></th>
												<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
												N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
												 + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
												N'<tr><th  width=250 align=left><H4>Order Date </th><th>:</th><th align=left>' 
												+ CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
												N'<tr><th  width=250 align=left><H4>Amount Before Edit </th><th>:</th><th align=left>' 
												+ cast(@PROLDAmount as varchar(50))  + '</H4></th>' + 
												N'<tr><th  width=250 align=left><H4>Amount After Edit </th><th>:</th><th align=left>' 
												+ cast(@PRAmount as varchar(50))  + '</H4></th>' +  
												N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
												+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
														
							SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert </TR></TR>'			
							
							If @emailid<>'' 
								Begin
									EXEC msdb.dbo.sp_send_dbmail
										@recipients=@emailid,
										@subject= @mailTitle, 
										@body_format = 'HTML',
										@body =@Mail_Msg
								End			 
								
			
			
			/* Ref No : 1 Start 
			DECLARE PRCursor CURSOR FOR
				 select  e.username,emailid from aapprovallevelmaster a inner join aapprovallevellimits b
					 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
					 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
					 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
					 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
					 Inner join ausers e on e.usergroupid=d.usergroupid
					 where 
					 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID  and c.interfaceid=2001
					 group by e.username,emailid 

						OPEN PRCursor 
						FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid

						WHILE @@FETCH_STATUS = 0 
						BEGIN 
							SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
							SET @Mail_Msg = @Mail_Msg + N'<P>Purchase Order Details After Edit.....'
								SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
												N'<TR><tr><th width=250 align=left><H4> Purchase Order No' + '</H4></th>
												<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
												N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
												 + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
												N'<tr><th  width=250 align=left><H4>Order Date </th><th>:</th><th align=left>' 
												+ CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
												N'<tr><th  width=250 align=left><H4>Order Amount </th><th>:</th><th align=left>' 
												+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
												N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
												+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
														
							SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
							
							If @emailid<>'' 
								Begin
									EXEC msdb.dbo.sp_send_dbmail
										@recipients=@emailid,
										@subject= @mailTitle, 
										@body_format = 'HTML',
										@body =@Mail_Msg
								End			 

						FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid
						END 
						CLOSE PRCursor 
						DEALLOCATE PRCursor
				 Ref No : 1 End  */
						
						
				/* PURCHASE ORDER AKNOWLEDGEMENT*/			
					SET @mailTitle=''
					SET @PRuserName=''
					SET @Mail_Msg=''
					SET @PRUserEmailid=''
					
					Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Purchase Order Has Been Changed -- Aknowledgement'
					
					SELECT @PRuserName=Username,@PRUserEmailid=EmailID from ausers where userid=@PRuserID
		 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>This is an aknowledgement for the below Purchase Order you have Edited.'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4> Purchase Order No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Date </th><th>:</th><th align=left>' 											
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount Before Edit </th><th>:</th><th align=left>' 
											+ cast(@PROLDAmount as varchar(50))  + '</H4></th>' + 
										    N'<tr><th  width=250 align=left><H4>Amount After Edit </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert </TR></TR>'			
						
						If @PRUserEmailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@PRUserEmailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End		
							

		End	---PR END	
END--prcancell


END
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
Use adminv2
Go
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'MagnoliaPurchaseRequest_Mail' AND type = 'TR')
BEGIN
    DROP TRIGGER MagnoliaPurchaseRequest_Mail
END
GO 
/*
Created By : Shine Das
Created On : 22.06.2012
Purpose	   : To send the approval required mail to authorised persons.
----------------------------------------------------------------------
Ref NO : 1
Modified By		: Shine Das	
On				: 13.08.2012
Purpose			: Aas per new requirement, Wataniya need to send alert mail only to first approving person. (normally will be
the lower level person.
*/
      
CREATE Trigger MagnoliaPurchaseRequest_Mail
On lopurchaseorderheader after Insert
As
Begin		---Trigger


--EMail Content...
Declare @userID INT
Declare @userCount INT
Declare @PRDeptID INT
Declare @POID INT
Declare @LimitID INT
Declare @ApprovalLevel INT
Declare @ApprovalLevelName Varchar(50)
Declare @mailTitle Varchar(200)
Declare @PONO Varchar(50)
Declare @Mail_Msg Varchar(8000)
Declare @Emailid Varchar(80)
Declare @PRAmount Numeric(18,2)
Declare @CurrentTransType Varchar(3)
Declare @PRuserID INT
Declare @PRuserName Varchar(50)
Declare @PRDateTime DATETIME              
Declare @PRRemarks Varchar(250)
Declare @DeptName Varchar(250)
Declare @PRUserEmailid Varchar(80)
 
SET @DeptName =''
select @POID = pohpoid, @PONO=pohpono, @PRDateTime =pohPodate, @CurrentTransType = pohtype, 
	   @PRAmount=pohvalue, @PRuserID=pohuserid,@PRDeptID=pohdepartmentID,@PRRemarks=pohremarks 
from inserted

SELECT @DeptName= departmentname from adepartmentmaster where DepartmentID=@PRDeptID

IF @CurrentTransType='R' 	---PR Start
	Begin	 
		Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Purchase Request Needs Your Approval'
	 
		
		
		select top 1 @PRuserName= a.LevelName,@emailid=emailid from aapprovallevelmaster a inner join aapprovallevellimits b
				 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e on e.usergroupid=d.usergroupid				 
				 where 
				 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID and c.interfaceid=2000
				 --group by e.username,emailid 
				   order by LevelNo desc

			 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>Following Purchase Request Needs Approval From You...'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4> Purchase Request No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Requested Date </th><th>:</th><th align=left>' 											
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @emailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 
							
		
		
		
		/* Ref NO : 1
		DECLARE PRCursor CURSOR FOR
			 select  e.username,emailid from aapprovallevelmaster a inner join aapprovallevellimits b
				 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e on e.usergroupid=d.usergroupid				 
				 where 
				 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID and c.interfaceid=2000
				 group by e.username,emailid 

					OPEN PRCursor 
					FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid

					WHILE @@FETCH_STATUS = 0 
					BEGIN 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>Following Purchase Request Needs Approval From You...'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4> Purchase Request No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Requested Date </th><th>:</th><th align=left>' 											
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @emailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 

					FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid
					END 
					CLOSE PRCursor 
					DEALLOCATE PRCursor
					*/
					
		/* PURCHASE REQUEST AKNOWLEDGEMENT*/			
					SET @mailTitle=''
					SET @PRuserName=''
					SET @Mail_Msg=''
					
					Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Purchase Request -- Aknowledgement'
					
					SELECT @PRuserName=Username,@PRUserEmailid=EmailID from ausers where userid=@PRuserID
		 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>This is an aknowledgement for the below Purchase Request you have made.'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4> Purchase Request No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Requested Date </th><th>:</th><th align=left>' 											
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @PRUserEmailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@PRUserEmailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 	 
					
					

	End	---PR END	
	
	
	IF @CurrentTransType='P' 	---PR Start
	Begin	 
		Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Purchase Order Needs Your Approval'
	 
		
		
		select  top 1 @PRuserName= a.LevelName,@emailid=emailid from aapprovallevelmaster a inner join aapprovallevellimits b
				 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e on e.usergroupid=d.usergroupid
				 where 
				 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID and c.interfaceid=2001
				 --group by e.username,emailid 
				order by LevelNo desc

 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>Following Purchase Order Needs Approval From You...'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4> Purchase Order No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Order Date </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Order Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @emailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 


		
 /* Ref NO : 1
		DECLARE PRCursor CURSOR FOR
			 select  e.username,emailid from aapprovallevelmaster a inner join aapprovallevellimits b
				 on a.levelid=b.levelid and a.InterfaceID=b.interfaceid and a.departmentid = b.departmentid
				 inner join aapprovallimitmaster c on c.limitid=b.limitid and 
				 c.InterfaceID=b.interfaceid and c.departmentid = b.departmentid
				 inner join aapprovalusergrouprights d on d.approvalrights = b.levelid and d.InterfaceID=b.interfaceid 
				 Inner join ausers e on e.usergroupid=d.usergroupid
				 where 
				 @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@PRDeptID and c.interfaceid=2001
				 group by e.username,emailid 

					OPEN PRCursor 
					FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid

					WHILE @@FETCH_STATUS = 0 
					BEGIN 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>Following Purchase Order Needs Approval From You...'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4> Purchase Order No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Order Date </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Order Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @emailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End			 

					FETCH NEXT FROM PRCursor INTO @PRuserName, @emailid
					END 
					CLOSE PRCursor 
					DEALLOCATE PRCursor
	*/			
					
					/* PURCHASE ORDER AKNOWLEDGEMENT*/			
					SET @mailTitle=''
					SET @PRuserName=''
					SET @Mail_Msg=''
					
					Set @mailTitle = 'Fi-es Mail Alert :  ' + cast(@PONO as varchar(50)) +' -- Purchase Order -- Aknowledgement'
					
					SELECT @PRuserName=Username,@PRUserEmailid=EmailID from ausers where userid=@PRuserID
		 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(@PRuserName as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>This is an aknowledgement for the below Purchase Order you have made.'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4> Purchase Order No' + '</H4></th>
											<th>:</th><th align=left>' + cast(@PONO as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Department </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),@DeptName,103)  + '</H4></th>' +
											N'<tr><th  width=250 align=left><H4>Date </th><th>:</th><th align=left>' 											
										    + CONVERT(VARCHAR(24),@PRDateTime,103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
											+ cast(@PRAmount as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(@PRRemarks as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If @PRUserEmailid<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@PRUserEmailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body =@Mail_Msg
							End		
							

	End	---PR END	
	
END
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
Use adminv2
Go
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'TransferOutAlerts' AND type = 'TR')
BEGIN
    DROP TRIGGER TransferOutAlerts
END
GO 
/*
Created By : Shine Das
Created On : 27.07.2012
Purpose	   : To send alerts to the respective persons in Recieving shop.
*/
      
CREATE Trigger TransferOutAlerts
On mesTransferoutHeader after Insert
As
Begin		---Trigger


	--EMail Content...
	Declare @userID INT
	Declare @userCount INT
	Declare @TORecAddedUserName Varchar(50)
	Declare @TORecAddedUserEmailid Varchar(80)
	Declare @TORecAddDetails Varchar(80)
	Declare @DeptID INT
	Declare @TOID INT
	
	Declare @mailTitle Varchar(200)
	Declare @TONO Varchar(50)
	Declare @Mail_Msg Varchar(8000)
	Declare @Emailid Varchar(80)
	Declare @TOAmount Numeric(18,9)
 
	Declare @TOuserID INT
	Declare @TOuserName Varchar(50)
	Declare @TOShopName Varchar(50)
	Declare @userName Varchar(50)
	Declare @TODateTime DATETIME              
	Declare @TORemarks Varchar(250)
	Declare @TOConfirmed BIT
	Declare @EmailuserID INT
	Declare @TOFromShopID INT
	Declare @TOToShopID INT
	Declare @AMOUNT Varchar(250)

 
	SET @Mail_Msg=''
    SET @TOID=0 
	SET @TORecAddedUserName=NULL
	SET @TORecAddedUserEmailid=NULL
	SET @TORecAddDetails=NULL
	
	select @TOID = isnull(TohID,0), @TONO=isnull(TohNo,''), @TODateTime =isnull(Tohdate,''),
	@TOConfirmed=isnull(TohTransfinished,0),@TOuserID=isnull(Tohrecadduser,0),
	@DeptID=isnull(TohdepartmentID,0),@TORemarks=isnull(Tohremarks,''),@userID=tohrecadduser,
	@TOFromShopID=isnull(TOHShopid,0),@TOTOShopID=isnull(TOHToShopid,0) from inserted
	
	IF @TOConfirmed<>1
	BEGIN
		RETURN
	END
	
	SELECT @TORecAddedUserName=isnull(username,''),@TORecAddedUserEmailid=isnull(EmailID,'') from lousers
		where userid=@userID
		
	IF @TORecAddedUserEmailid<>''
		BEGIN
			SET @TORecAddDetails = cast(isnull(@TORecAddedUserName,'') as varchar(50)) + ' (Email: ' + 
			cast(isnull(@TORecAddedUserEmailid,'') as varchar(50)) + ' )'
		END
	ELSE
		BEGIN
			SET @TORecAddDetails = cast(isnull(@TORecAddedUserName,'') as varchar(50))	 
		END
	
  
 
	select @TOAmount=isnull(sum(mtd.TODissuedGoodQty * mtd.TodCostPrice),0) from mesTransferoutHeader mth inner join 
		mesTransferoutdetail mtd on mth.tohid=mtd.todid and mth.tohshopid=mtd.todshopid and
		mth.tohtoshopid=mtd.todtoshopid where mth.tohcancelled=0 and mth.tohid=@TOID 
		and mth.TOHShopid=@TOFromShopID  and mth.TOHtoShopid=@TOTOShopID
 
	insert into tbltest values(@TOAmount)
		Set @mailTitle = 'Fi-es Mail Alert : An Issue (' + cast(isnull(@TONO,'') as varchar(50)) + ') from ' + 
		isnull(@TOShopName,'') + ' is pending for you to raise a GRN (TransferIn)'
	 
		DECLARE PRCursor CURSOR FOR
			 select isnull(Userid,0) Userid from loEmailalertUsers where interfaceid=1601 and fromshopid=@TOFromShopID
			 and  ToShopid=@TOTOShopID

					OPEN PRCursor 
					FETCH NEXT FROM PRCursor INTO @EmailuserID

					WHILE @@FETCH_STATUS = 0 
					BEGIN 
					
						SELECT @userName=isnull(username,''),@Emailid=isnull(EmailID,'') from lousers
						where userid=@EmailuserID
						--+ cast(isnull(@TOAmount,0) as varchar(50))  + '</H4></th>' + 
						SET @Mail_Msg= N'<H4>Dear '  + CAST(isnull(@userName,'') as varchar(50)) + ',</H4> <PR>'  
						SET @Mail_Msg = @Mail_Msg + N'<P>' + isnull(@TOShopName,'') + ' has issued :'
							SET @Mail_Msg = @Mail_Msg + N'<P> <table border="0">' +
											N'<TR><tr><th width=250 align=left><H4>Transfer Out No' + '</H4></th>
											<th>:</th><th align=left>' + cast(isnull(@TONO,'') as varchar(50)) + '</th>' + 
											N'<tr><th  width=250 align=left><H4>Date </th><th>:</th><th align=left>' 
										    + CONVERT(VARCHAR(24),isnull(@TODateTime,''),103)  + '</H4></th>' +
										    N'<tr><th  width=250 align=left><H4>Amount </th><th>:</th><th align=left>' 
											+ cast(isnull(@TOAmount,'') as varchar(50))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Remarks </th><th>:</th><th align=left>' 
											+ cast(isnull(@TORemarks,'') as varchar(250))  + '</H4></th>' + 
											N'<tr><th  width=250 align=left><H4>Transfer Out Done By </th><th>:</th><th align=left>'  
											+ cast(isnull(@TORecAddDetails,'') as varchar(250))  + '</H4></th>'
													
						SET @Mail_Msg = @Mail_Msg + N'<TR><TR> Regards,' + '<TR> Fi-es Mail Alert '			
						
						If isnull(@emailid,'')<>'' 
							Begin
								EXEC msdb.dbo.sp_send_dbmail
									@recipients=@emailid,
									@subject= @mailTitle, 
									@body_format = 'HTML',
									@body = @Mail_Msg
							End			 

					FETCH NEXT FROM PRCursor INTO @EmailuserID
					END 
					CLOSE PRCursor 
					DEALLOCATE PRCursor

 
	
END
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--FINDVIEW
--VIEW CREATIONS AND ALTERATIONS

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

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


IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwshopservicesales')
   DROP view dbo.vwshopservicesales
GO

--Last Modified on  : 19/10/2004    
--Modified by  : Aneesh  
------------------------------------------------------------------------------------------           
-- Modified by  : Bijesh.B  
-- Date         : 19/08/2011  
-- RefNo        : RefNo-1   
-- Ticket Id    : JSZ-828136 (SHEESHA)  
-- Description  : Need UserWise selection for Cash Denomination interface  
--              : siUserID column included  
------------------------------------------------------------------------------------------ 
-- Modified by  : AADYAKUMAR.D.V 
-- Date         : 27/06/2012 
-- RefNo        : RefNo-2   
-- Ticket Id    : CBX-451956  
-- Description  : Added tax 
------------------------------------------------------------------------------------------           
     
CREATE View dbo.vwshopservicesales As  
    Select sicompanyid, sishopid, aiinvoicedate As siinvoicedate, aiinvoiceno, siinvoiceid,     
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then     
        (Sum(siServiceQty * siAmount))+ ISNULL(aiTaxAmount,0)-IsNull(aiDiscount,0)  --RefNo-2  
    Else     
        (Sum((siServiceQty * siAmount) + siClearingCommAmt)) -IsNull(aiDiscount,0) End  
        As siamount, Sum(aiSettledamount) Settledamount ,     
  
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then     
        (Sum(siServiceQty * siAmount)) +ISNULL(aiTaxAmount,0) -IsNull( aiDiscount,0) * aiexchangerate --RefNo-2 
    Else     
        (Sum((siServiceQty * siAmount) + siClearingCommAmt)) -IsNull(aiDiscount,0) End  
        * aiexchangerate As sicamount,     
       
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then     
        (Sum(siServiceQty * siAmount))+ISNULL(aiTaxAmount,0) -IsNull( aiDiscount,0) * aidepexrate --RefNo-2 
    Else     
        (Sum((siServiceQty * siAmount) + siClearingCommAmt)) -IsNull(aiDiscount,0) End  
        * aidepexrate As sidamount       
    ,ISNULL(siUserID,0) as UserID    
    From LOsServiceInvoiceDetails, LOsAccountsInvoiceHeader  
    Where aicancelled=0 And aiproforma=0 And aiinvoiceid = siinvoiceid And aishopid = sishopid    
    Group By sicompanyid, sishopid, aiinvoicedate,   
    siinvoiceid, aiinvoiceno, aiexchangerate,  aidepexrate,aiDiscount,  
    Convert(Int, IsNull(aiCashPaidByShop,0)),ISNULL(siUserID,0),aiTaxAmount

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

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionWithMarginGSTSeparately')
   DROP view dbo.vwDailySalesCollectionWithMarginGSTSeparately
GO
        
--Modified on           : 04/09/2004                  
--Modified by           : Hariharan                   
--Comments              : Added LOsAccountsInvoiceHeader                  
--   : Added lnvoiceheader - Id grouping                  
--   : included service details of service boooking invoices                    
--   : Corrected join condition of ashops with LOsAccountsInvoiceHeader                  
--   : Corrected the service invoice query to consider the repinvdtype field                
---------------------------------------------------------------------------------------                        
--Modified on                  : 22/11/2010               
--Modified by                  : Nidheesh P V                
--Comments                     : AddedF&B               
---------------------------------------------------------------------------------------                        
--RefNo        : RefNo-2        
--Modified by  : Bijesh.B        
--Date         : 16/06/2011, 21/06/2011        
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)        
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-3        
--Modified by  : Nidheesh P V       
--Date         : 16/06/2011        
--Comments     : Used -costprice instead of costprice       
--Modified Area: Daily Sales Report      
----------------------------------------------------------------------------------------------            
--RefNo        : RefNo-4      
--Modified by  : Bijesh.B      
--Date         : 29/07/2011      
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong      
--             : since, Special invoice return after desp, reqqty is negative,      
--     -1 is multiplied with reqqty      
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-5        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 19/01/2012  
--Comments     : Modified F&B part.  
----------------------------------------------------------------------------------------------         
----------------------------------------------------------------------------------------------         
--Created by   : Bijesh.B   
--Date         : 29/03/2012  
--Ticket id    : JDJ-400367 (new report (rptdailysalescollectionGSTSeparately) for sonee - GST separation)  
--Comments     : Created new view and report (Copy of vwDailySalesCollectionWithMargin)  
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-6        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 26/06/2012  
--Comments     : Exchage rate multiplication problem in POS  
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B    
--Date         : 07/07/2012  
--Comments     : Corrected Margin value for credit invoice
----------------------------------------------------------------------------------------------       
  
create VIEW [dbo].[vwDailySalesCollectionWithMarginGSTSeparately] AS                  
Select                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.poshbilldate, convert(numeric(18,8),sum(cashsales)) cashsales,                  
 convert(numeric(18,8),sum(dcashsales)) dcashsales,                   
 convert(numeric(18,8),sum(ccashsales)) ccashsales,                  
 convert(numeric(18,8),sum(creditsales)) creditsales,                  
 convert(numeric(18,8),sum(dcreditsales)) dcreditsales,                   
 convert(numeric(18,8),sum(ccreditsales)) ccreditsales,                   
 convert(numeric(18,8),sum(costvalue)) costvalue,                  
 convert(numeric(18,8),sum(dcostvalue)) dcostvalue,                   
 convert(numeric(18,8),sum(ccostvalue)) ccostvalue,                   
 convert(numeric(18,8),sum(margin)) margin,                  
 convert(numeric(18,8),sum(dmargin)) dmargin, 
 convert(numeric(18,8),sum(cmargin)) cmargin,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid        
 --RefNo-2 start -------------------------        
,convert(numeric(18,8),sum(PdChequeSales)) PdChequeSales,        
convert(numeric(18,8),sum(dPdChequeSales)) dPdChequeSales,        
convert(numeric(18,8),sum(cPdChequeSales)) cPdChequeSales,        
--RefNo-2 ends -------------------------        
convert(numeric(18,8),sum(GSTAmount))GSTAmount,  
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,  
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount  
from                   
 (                  
  select                   
   shopname, poshShopID, poshbilldate,   
   --convert(numeric(18,8),sum(posdunitprice )) cashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)) ccashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dcashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8),sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -  
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))))) - sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -  
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   departmentname, poshdepartmentid  departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d                   
  where                   
   poshBillid=posdBillid and poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=0 --RefNo-2  if No PD Cheque Amt involved                           
  group by                   
   shopname, departmentname, poshdepartmentid, poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,poshBillid                  
        
--RefNo-2 Start --------------------------------------------        
--CASH + PD CHEQUE -> Taking only cash amount        
union all        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   --convert(numeric(18,8),                   
   --sum(posdunitprice )) cashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshdepexrate)) dcashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshexchangerate)) ccashsales,        
     
   --convert(numeric(18,8),sum(posdunitprice)-pdCheque.PosBankAmount) cashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) dcashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) ccashsales,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8), sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -   
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))))) -   
        sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshdepexrate)) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -   
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
            
   departmentname, poshdepartmentid  departmentid                  
   --,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dPdChequeSales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) cPdChequeSales  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved        
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                            
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
  
/*        
union all        
--CASH + PD CHEQUE -> Taking only Cheque amount        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,        
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales,      
   /*      
   sum(posdcostprice * posdquantity) costvalue,                   
         
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
        
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
        
   (convert(numeric(18,8), sum(posdunitprice ))) -                   
   sum(posdcostprice*posdquantity) margin,      
         
   (convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -   
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin,       
         
   (convert(numeric(18,8), sum(posdunitprice * poshexchangerate))) -       
   sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   */      
   0.0 costvalue,0.0 dcostvalue,0.0 ccostvalue,       
   0.0 margin,0.0 dmargin,0.0 cmargin,        
   departmentname, poshdepartmentid  departmentid,                  
    pdCheque.PosBankAmount as PdChequeSales,        
   (pdCheque.PosBankAmount * poshdepexrate) as  dPdChequeSales,        
   (pdCheque.PosBankAmount * poshexchangerate) as cPdChequeSales        
  from                
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved          
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                          
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
--RefNo-2 ends --------------------------------------------        
*/                  
 union all                  
                   
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,             
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -                   
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -             
		 sum(isnull(idcostprice*idquantity,0)))) margin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from                   
   losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid     
   left outer join                   
   (select                  
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount                  
   from                  
    losInvoiceOC                   
   group by                  
   ioShopID,ioInvoiceID) ocd                   
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
   ashops s, adepartmentmaster d                   
  where                   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
 union all                  
                  
  select                   
   shopname, ihShopID, ihinvoicedate,                  
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) Cashsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,         
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,                   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,             
   0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -                   
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -             
		sum(isnull(idcostprice*idquantity,0)))) margin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from                   
   losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join                   
   (select                  
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount        
   from                  
    losInvoiceOC                   
   group by                  
   ioShopID,ioInvoiceID) ocd                   
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
   ashops s, adepartmentmaster d                   
  where                   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=1 and ihdepartmentid = d.departmentid and ihtype ='i'                  
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
                  
 union all                  
   select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehexchangerate)) ccashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
   0.0 creditsales,0.0 dcreditsales , 0.0 ccreditsales , sum(sedcostprice * sedquantity) costvalue,                  
   sum(sedcostprice * sedquantity) * sehdepexrate dcostvalue,                   
   sum(sedcostprice * sedquantity) * sehexchangerate ccostvalue,                  
   --convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedquantity) margin,  
   --convert(numeric(18,8), sum(sedunitprice* sehdepexrate)) -                   
   --sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   --convert(numeric(18,8), sum(sedunitprice * sehexchangerate )) -   
   --sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) - sum(sedcostprice * sedquantity) margin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) -                   
          sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) -   
          sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
    departmentname, sehdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d            
  where                   
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange = 'E' and sehshopid = shopid and sehdepartmentid = d.departmentid          
  group by      
   shopname, sehshopid, departmentname, sehdepartmentid, sehexchangedate ,                  
   departmentname,sehdepexrate, sehexchangerate,sehExchangeID                  
 union all                  
       
 -- RefNo-4 start  commented below      
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  sum(idunitprice )) cashsales, convert(numeric(18,8),                   
 ------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,8),                   
 ------  sum(idunitprice * ihexchangerate)) ccashsales,                  
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  (convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                   
 ------  (convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                   
 ------  (convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin, departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  ihdepartmentid =d.departmentid and idratetype=0 and ihproforma=0 and                   
 ------  ihshopid = shopid and ihcashinvoice=1 and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, departmentname, ihdepartmentid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
 ------ union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                   
 ------  0.0 ccashsales, convert(numeric(18,8), sum(idunitprice )) creditsales,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate)) dcreditsales,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate)) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                  
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                  
 ------  convert(numeric(18,8), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate) - sum(idcostprice*reqqty) * ihexchangerate) cmargin,                   
 ------  departmentname, ihDepartmentId departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  idratetype=0 and ihproforma=0 and ihshopid = shopid and                   
 ------  ihcashinvoice=0 and ihDepartmentId = d.departmentid                  
 ------  and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname, ihinvoicedate ,                   
 ------  ihexchangerate, ihdepexrate,ihInvoiceid                  
                  
 ------union all                  
 -- RefNo-4 ends      
                  
  select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),-sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehexchangerate)) ccashsales,                  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(-sedcostprice * sedExchangeQty) costvalue,    --RefNo-3              
   sum(-sedcostprice * sedExchangeQty) * sehdepexrate dcostvalue, sum(-sedcostprice * sedExchangeQty)     --RefNo-3             
   * sehexchangerate ccostvalue,  
    ---(convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedExchangeQty)) margin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -                   
    --    sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -   
    --    sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
           sum(sedcostprice * sedExchangeQty)) margin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -                   
        sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
        sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
  
   departmentname, sehdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d                   
  where                   
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid                   
   and sehdepartmentid = d.departmentid                   
  group by                   
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,                  
   sehdepexrate,sedExchangeid                  
 union all       
       
 -- RefNo-4 start                  
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  -(sum(idunitprice ))) cashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihexchangerate))) ccashsales,                   
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(idcostprice * abs(reqqty)) costvalue,                   
 ------  sum(idcostprice * abs(reqqty)) * ihdepexrate dcostvalue, sum(idcostprice * abs(reqqty)) *                   
 ------  ihexchangerate ccostvalue,  -((convert(numeric(18,8), sum(idunitprice ))) -            
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0                    
 ------  and ihproforma=0 and ihshopid = shopid and ihTransfinished = 1                   
 ------  and ihcashinvoice=1 AND IDratetype=1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihdepartmentid, departmentname, ihshopid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
          
 ------union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice ))) creditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihdepexrate))) dcreditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihexchangerate))) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                   
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8),                   
 ------  sum(idunitprice ))) -  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                   
 ------  IHCANCELLED = 0 and ihproforma = 0 and ihshopid = shopid and                   
 ------  ihcashinvoice = 0 and idratetype = 1 and ihtransfinished = 1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname,                  
 ------  ihinvoicedate , ihexchangerate, ihdepexrate,ihInvoiceid                  
                  
 ------union all                  
      
-- special Invoice (cash)        
select         
shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccashsales,    
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales,   
  
0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty) margin,             
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,        
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty))* ihexchangerate cmargin,  
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                    
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all                                      
      
-------- special invoice - return before despatch                          
select shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,       
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-sum(idcostprice * reqqty) costvalue ,      
-sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
-sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
     
union all                                      
                                   
-- Special invoice return  - after desp                                    
select shopname,                                     
 ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,     
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                        
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1         
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
-- special Invoice (credit)      
union all      
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccreditsales,    
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
       
 sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice)))-sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))))-sum(idcostprice*reqqty) margin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                    
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice <>1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all                                      
      
-- special invoice - return before despatch                          
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,  
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,     
  
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
 -sum(idcostprice * reqqty) costvalue ,      
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) margin,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice <>1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                          
union all                                      
                                   
-- Special invoice return  - after desp                                    
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate))dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate))ccreditsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)dcreditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)ccreditsales,       
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
--idUnitPrice, idItemTaxAmount  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice <>1                                     
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
 -- RefNo-4 ends       
  union all                 
  select                   
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
   -- -convert(numeric(18,8), (sum(GRNDunitprice ))) creditsales,                   
   -- -convert(numeric(18,8), (sum(GRNDunitprice * grnhdepexRate))) dcreditsales,                   
   -- -convert(numeric(18,8), (sum(GRNDunitprice * grnhExchangeRate))) ccreditsales,   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) creditsales,                   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   
   -sum(grncostprice*grndquantity) costvalue, - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                   
   -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,                   
   -- -(convert(numeric(18,8), (sum(GRNDunitprice )))-sum(grncostprice*grndquantity)) margin,  
   -- -(convert(numeric(18,8), (sum(GRNDunitprice ))) -                   
   --    sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
   -- -(convert(numeric(18,8),(sum(GRNDunitprice ))) -  
   --     sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,                   
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))))-  
           sum(grncostprice*grndquantity)) margin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -                   
       sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -  
        sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,                   
   departmentname, grnhdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
    -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  from                   
   losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d                   
  where               
   GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0                   
   and grnhshopid = shopid and grnhdepartmentid = d.departmentid                   
  group by                   
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,                   
   grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID                  
  --hari added to include the service booking invoice parts replaced items                  
 UNION ALL                  
                  
  select                   
   shopname, repinvdshopid, serinvhdate,  
   --convert(numeric(18,8),sum(repinvdrate* repinvdqty)) cashsales,  
   --convert(numeric(18,8),sum(repinvdrate* seinvhdepexrate * repinvdqty)) dcashsales,                  
   --convert(numeric(18,8),sum(repinvdrate* serinvhcmpexrate * repinvdqty)) ccashsales,                  
   convert(numeric(18,8),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))) cashsales,  
   convert(numeric(18,8),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))* seinvhdepexrate) dcashsales,            
   convert(numeric(18,8),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate) ccashsales,            
  
   0.0 creditsales, 0.0 dcreditsales , 0.0 ccreditsales ,  sum(repinvdcostprice * repinvdqty) costvalue,                   
   sum(repinvdcostprice * repinvdqty) * seinvhdepexrate  dcostvalue,                   
   sum(repinvdcostprice * repinvdqty) *serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -  
   --  sum(repinvdcostprice * repinvdqty),                   
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,   
   --convert(numeric(18,8),(sum(repinvdrate  * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty),             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,            
  
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
 ,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d                   
  where                   
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1                  
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, serinvhDepartmentid,                   
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid                   
                  
 union all                  
                  
  select                   
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , (sum(repinvdrate* repinvdqty))) creditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * seinvhdepexrate * repinvdqty))) dcreditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * serinvhcmpexrate * repinvdqty))) ccreditsales ,   
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
                     
   sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*                   
   seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty), convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty) * seinvhdepexrate , convert(numeric(18,8) ,                   
   --( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate ,                   
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * seinvhdepexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate,  
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
 ,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader,                   
   ashops s, adepartmentmaster d where serinvhid = repinvinvoiceid and                   
   serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is null                   
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid                    
   and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,                  
   serinvhcmpexrate ,serinvhid                   
  union all                  
  
  --service Details                  
  select                   
   shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , serinvhserviceamt) creditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcreditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccreditsales ,     
   convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) creditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate) dcreditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate) ccreditsales ,             
  
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,                   
   convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) ,             
   convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))*seinvhdepexrate) ,             
   convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))*serinvhcmpexrate) ,             
  
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount    
  from                   
   losserviceinvheader, ashops s, adepartmentmaster d                   
  where                   
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                   
  union all                  
    
  --service Details                  
  select                   
   shopname, serinvhshopid, serinvhdate,  
   --convert(numeric(18,8) , serinvhserviceamt) cashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccashsales ,                   
   convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0))cashsales ,             
   convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate)dcashsales ,             
   convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate)ccashsales ,             
     
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                       
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,    
   convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)),             
   convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,             
   convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) *  serinvhcmpexrate) ,             
  
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount  
  from                   
   losserviceinvheader, ashops s, adepartmentmaster d                   
  where                   
   serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                  
                  
 union all                  
  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002                  
  --credit           
  select           
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,                   
   0.0 ccashsales,                  
    convert(numeric(18,8), sum(redunitprice)) creditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehdepexrate)  dcreditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehexchangerate) ccreditsales,
   sum(redcostprice * redquantity) costvalue,                   
   sum(redcostprice * redquantity) * rehdepexrate dcostvalue, 
   sum(redcostprice * redquantity) * rehexchangerate ccostvalue,
   (convert(numeric(18,8), sum(redunitprice ))) -  sum(redcostprice * redquantity) margin,
   (convert(numeric(18,8), sum(redunitprice * rehdepexrate))) -                   
		sum(redcostprice * redquantity) * rehdepexrate dmargin,
   (convert(numeric(18,8), sum(redunitprice * rehexchangerate))) - 
		sum(redcostprice * redquantity) * rehexchangerate cmargin,                   
   departmentname, rehdepartmentid                  
 ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,0,0,0  
  from                   
   losExportDetail, losExportHeader, ashops s, adepartmentmaster d                   
  where                   
   rehExportID = redExportID and rehshopid = redshopid AND                   
   reHCANCELLED=0 and rehtype ='i' and                  
   rehproforma=0 and rehshopid = shopid and rehcashinvoice=0 and                   
   rehdepartmentid = d.departmentid                   
  group by                   
   shopname, rehshopid, departmentname, rehdepartmentid, rehExportDate,                   
   rehdepexrate, rehexchangerate,rehExportID                   
            
 union all                  
 -- added From Vwcashsales -Margin Not calculating                  
                   
 select                   
  s.shopname, vws.sishopid, vws.siinvoicedate,                   
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,                   
  convert(numeric(18,8),sum(vws.siamount) * aidepexrate) as  dcashsales,                   
  convert(numeric(18,8),sum(vws.siamount) * aiexchangerate) as ccashsales,                  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
   0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
  convert(numeric(18,8),sum(vws.siamount)) as margin,                   
  convert(numeric(18,8),sum(vws.siamount) * aidepexrate) as  dmargin,                   
  convert(numeric(18,8),sum(vws.siamount) * aiexchangerate) as cmargin,                  
  d.departmentname,lah.aidepartmentid  departmentid                   
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
  , sum(vws.dGSTAmount) as dGSTAmount  
  , sum(vws.cGSTAmount) as cGSTAmount  
 from                   
  vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d ,ashops s                  
 where                   
  aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
  aishopid = sishopid and lah.aicashinvoice=1 and                   
  lah.aidepartmentid =d.departmentid and s.departmentid = d.departmentid                  
  and aiShopId = s.ShopId                  
 group by                   
  s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid, vws.siinvoicedate                  
  ,aidepexrate, aiexchangerate               
 union all                  
                  
    select s.shopname, vws.sishopid, vws.siinvoicedate,                   
    0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
    convert(numeric(18,8),sum(vws.siamount)) as creditsales,                   
    convert(numeric(18,8),sum(vws.siamount)) as dcreditsales,                   
    convert(numeric(18,8),sum(vws.siamount)) as ccreditsales,                  
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
    convert(numeric(18,8),sum(vws.siamount)) as margin,                   
    convert(numeric(18,8),sum(vws.siamount)) as dmargin,                 
    convert(numeric(18,8),sum(vws.siamount)) as cmargin,                  
    d.departmentname,lah.aidepartmentid  departmentid                   
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
    , sum(vws.dGSTAmount)as dGSTAmount  
    , sum(vws.cGSTAmount)as cGSTAmount  
    from vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d,ashops s                  
    where aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
    aishopid = sishopid and lah.aicashinvoice=0 and lah.aidepartmentid =d.departmentid                  
    and s.departmentid = d.departmentid and s.ShopId = aiShopId group by                       
    s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid,vws.siinvoicedate,aiinvoiceid,
    aidepexrate                   
                   
    UniOn All -- added from vwCashSales                 
    --Shop debit credit notes and handling debit notes which are debit to the                
    -- customer and hence act as invoices to be settled                      
    Select  s.shopname,losdcnshopid,losdcndate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
    COnvert(numeric(18,8),Sum(losDCNAmount))  creditsales,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dcreditsales,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  ccreditsales,               
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    COnvert(numeric(18,8),Sum(losDCNAmount))  margin,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dmargin,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  cmargin,              
 d.departmentname,losdcndepartmentid                   
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2    
       ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount      
    From Ashops s,  losdebitcreditnote, adepartmentmaster d               
    Where  s.shopid = losdcnshopid And s.accountable Is Not Null                   
    And d.DepartmentID = losdcndepartmentid And losdcncancelled =0                    
    And losdcndebit =1  Group By s.shopname,d.departmentname,losdcnshopid,                  
    losdcndate, losdepexrate, losexchangerate,losdcndepartmentid              
              
    --hq serivce invoice dOne for shop                    
    Union all              
               
    Select  null, 0,ai.invoicedate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  creditsales,                     
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dcreditsales,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  ccreditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)ccreditsales,         
  
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  margin,                     
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dmargin,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  cmargin,   
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)) * exchangerate)cmargin,        
                 
    d.departmentname,ai.departmentid           
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
     ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount   
     ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,  
      convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount  
  
  From accountsinvoiceheader ai, serviceinvoicedetails ser ,adepartmentmaster d               
    Where ai.invoiceid = ser.invoiceid And ai.companyid =                     
    ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0             
    and ai.departmentid = d.departmentid and ai.companyid = d.companyid               
    Group By  ai.invoicedate,depexrate,exchangerate,              
    d.departmentname,ai.departmentid              
        
  
 ----F&B---------------------------   
 --RefNo-5----------------------------------------------start----------------------------------------------------------------------------  
 ----------------------------------------  
 -- select v.* from        
 --(        
--select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales,        
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 --inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 --UNION ALL        
        
 --select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales,        
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 --inner join aitem a on a.itemid=fb_pd_dishid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 --where fb_pd_AddedItemtype=2        
 --)v       
  
/*  
union all  
  select shopname,poshShopID,poshBillDate,Cashsales,DepCashsales,ComCashsales,Creditsales,DepCreditsales,  
 ComCreditsales,costprice,dcostprice,ccostprice,margin,dmargin,cmargin,deptname,deptid,  
PdChequeSales,dPdChequeSales,cPdChequeSales  from  
 (        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid) costprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2        
  fb_pd_processdetailid  
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 UNION ALL        
        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2   
  fb_pd_processdetailid       
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 inner join aitem a on a.itemid=fb_pd_dishid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 where fb_pd_AddedItemtype=2        
  
  
 )  
  
  v        
 --RefNo-5----------------------------------------------end----------------------------------------------------------------------------  
  ----------------------------------------                  
  */  
     
 )cashcreditcollection      
group by                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid,                   
 cashcreditcollection.poshbilldate   
  
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwshopservicesalesWithOutGST')
   DROP view dbo.vwshopservicesalesWithOutGST
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 --Last Modified on  : 19/10/2004    
--Modified by  : Aneesh  
------------------------------------------------------------------------------------------           
-- Modified by  : Bijesh.B  
-- Date         : 19/08/2011  
-- RefNo        : RefNo-5   
-- Ticket Id    : JSZ-828136 (SHEESHA)  
-- Description  : Need UserWise selection for Cash Denomination interface  
--              : siUserID column included  
------------------------------------------------------------------------------------------           
--RefNo        : Newly created view (copy of vwshopservicesales)  
--Modified by  : Bijesh.B  
--Date         : 13/03/2012,11/04/2012 (addes sum() in GST Amount)  
--Ticket id    : JDJ-400367 (Sonee)  
--comments     : Need to show GST separately  
----------------------------------------------------------------------------------------------     
--Modified by  : Bijesh.B  
--Date         : 09/07/2-12 
--Ticket id    : JDJ-400367 (Sonee)  
--comments     : Removde sum() in GST Amount, corrected sicamount and sidamount
----------------------------------------------------------------------------------------------     
    
create View vwshopservicesalesWithOutGST As  
    Select sicompanyid, sishopid, aiinvoicedate As siinvoicedate, aiinvoiceno, siinvoiceid,     
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then     
        ((Sum(siServiceQty * siAmount)) -IsNull(aiDiscount,0))   
    Else     
        (Sum((siServiceQty * siAmount) + siClearingCommAmt)) -IsNull(aiDiscount,0)  End  
        As siamount,

    Sum(aiSettledamount) Settledamount ,     
  
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then     
        Sum( ((siServiceQty * siAmount)- IsNull(aiDiscount,0)) * aiexchangerate)
    Else     
        Sum( (((siServiceQty * siAmount) + siClearingCommAmt) 
              -IsNull(aiDiscount,0))* aiexchangerate) End  As sicamount,     
       
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then     
        Sum(((siServiceQty * siAmount) -IsNull(aiDiscount,0))* aidepexrate) 
    Else     
        Sum((((siServiceQty * siAmount) + isnull(siClearingCommAmt,0)) 
			 -IsNull(aiDiscount,0))* aidepexrate)
			 End As sidamount       
		
    ,ISNULL(siUserID,0) as UserID  
    ,(isnull(aiTaxAmount,0)) GSTAmount  
    ,(isnull(aiTaxAmount,0) * aidepexrate) as dGSTAmount  
    ,(isnull(aiTaxAmount,0) * aiexchangerate) as cGSTAmount    
    From LOsServiceInvoiceDetails, LOsAccountsInvoiceHeader  
    Where aicancelled=0 And aiproforma=0 And aiinvoiceid = siinvoiceid And aishopid = sishopid   
    Group By sicompanyid, sishopid, aiinvoicedate,   
    siinvoiceid, aiinvoiceno, aiexchangerate,  aidepexrate,aiDiscount,isnull(aiTaxAmount,0),  
    Convert(Int, IsNull(aiCashPaidByShop,0)),ISNULL(siUserID,0)  
    

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

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionWithMarginGSTSeparately')
   DROP view dbo.vwDailySalesCollectionWithMarginGSTSeparately
GO
 
         
--Modified on           : 04/09/2004                  
--Modified by           : Hariharan                   
--Comments              : Added LOsAccountsInvoiceHeader                  
--   : Added lnvoiceheader - Id grouping                  
--   : included service details of service boooking invoices                    
--   : Corrected join condition of ashops with LOsAccountsInvoiceHeader                  
--   : Corrected the service invoice query to consider the repinvdtype field                
---------------------------------------------------------------------------------------                        
--Modified on                  : 22/11/2010               
--Modified by                  : Nidheesh P V                
--Comments                     : AddedF&B               
---------------------------------------------------------------------------------------                        
--RefNo        : RefNo-2        
--Modified by  : Bijesh.B        
--Date         : 16/06/2011, 21/06/2011        
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)        
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-3        
--Modified by  : Nidheesh P V       
--Date         : 16/06/2011        
--Comments     : Used -costprice instead of costprice       
--Modified Area: Daily Sales Report      
----------------------------------------------------------------------------------------------            
--RefNo        : RefNo-4      
--Modified by  : Bijesh.B      
--Date         : 29/07/2011      
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong      
--             : since, Special invoice return after desp, reqqty is negative,      
--     -1 is multiplied with reqqty      
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-5        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 19/01/2012  
--Comments     : Modified F&B part.  
----------------------------------------------------------------------------------------------         
----------------------------------------------------------------------------------------------         
--Created by   : Bijesh.B   
--Date         : 29/03/2012  
--Ticket id    : JDJ-400367 (new report (rptdailysalescollectionGSTSeparately) for sonee - GST separation)  
--Comments     : Created new view and report (Copy of vwDailySalesCollectionWithMargin)  
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-6        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 26/06/2012  
--Comments     : Exchage rate multiplication problem in POS  
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B    
--Date         : 07/07/2012  
--Comments     : Corrected Margin value for credit invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-7 
--Date         : 09/07/2012  
--Comments     : Corrected Margin value for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-8 
--Date         : 09/07/2012  
--Comments     : Corrected gst amount for service invoice
----------------------------------------------------------------------------------------------       

create VIEW [dbo].[vwDailySalesCollectionWithMarginGSTSeparately] AS                  
Select                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.poshbilldate, convert(numeric(18,8),sum(cashsales)) cashsales,                  
 convert(numeric(18,8),sum(dcashsales)) dcashsales,                   
 convert(numeric(18,8),sum(ccashsales)) ccashsales,                  
 convert(numeric(18,8),sum(creditsales)) creditsales,                  
 convert(numeric(18,8),sum(dcreditsales)) dcreditsales,                   
 convert(numeric(18,8),sum(ccreditsales)) ccreditsales,                   
 convert(numeric(18,8),sum(costvalue)) costvalue,                  
 convert(numeric(18,8),sum(dcostvalue)) dcostvalue,                   
 convert(numeric(18,8),sum(ccostvalue)) ccostvalue,                   
 convert(numeric(18,8),sum(margin)) margin,                  
 convert(numeric(18,8),sum(dmargin)) dmargin, 
 convert(numeric(18,8),sum(cmargin)) cmargin,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid        
 --RefNo-2 start -------------------------        
,convert(numeric(18,8),sum(PdChequeSales)) PdChequeSales,        
convert(numeric(18,8),sum(dPdChequeSales)) dPdChequeSales,        
convert(numeric(18,8),sum(cPdChequeSales)) cPdChequeSales,        
--RefNo-2 ends -------------------------        
convert(numeric(18,8),sum(GSTAmount))GSTAmount,  
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,  
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount  
from                   
 (                  
  select                   
   shopname, poshShopID, poshbilldate,   
   --convert(numeric(18,8),sum(posdunitprice )) cashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)) ccashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dcashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8),sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -  
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))))
	 - sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -  
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   departmentname, poshdepartmentid  departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d                   
  where                   
   poshBillid=posdBillid and poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=0 --RefNo-2  if No PD Cheque Amt involved                       
  group by                   
   shopname, departmentname, poshdepartmentid, poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,poshBillid                  
        
--RefNo-2 Start --------------------------------------------        
--CASH + PD CHEQUE -> Taking only cash amount        
union all        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   --convert(numeric(18,8), 
   --sum(posdunitprice )) cashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshdepexrate)) dcashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshexchangerate)) ccashsales,        
     
   --convert(numeric(18,8),sum(posdunitprice)-pdCheque.PosBankAmount) cashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) dcashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) ccashsales,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8), sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -   
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))))) -   
        sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshdepexrate)) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -   
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
            
   departmentname, poshdepartmentid  departmentid                  
   --,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dPdChequeSales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) cPdChequeSales  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved        
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                            
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
  
/*        
union all        
--CASH + PD CHEQUE -> Taking only Cheque amount        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,        
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales,      
   /*      
   sum(posdcostprice * posdquantity) costvalue,                   
         
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
        
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
        
   (convert(numeric(18,8), sum(posdunitprice ))) -                   
   sum(posdcostprice*posdquantity) margin,      
         
   (convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -   
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin,       
         
   (convert(numeric(18,8), sum(posdunitprice * poshexchangerate))) -       
   sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   */      
   0.0 costvalue,0.0 dcostvalue,0.0 ccostvalue,       
   0.0 margin,0.0 dmargin,0.0 cmargin,        
   departmentname, poshdepartmentid  departmentid,                  
    pdCheque.PosBankAmount as PdChequeSales,        
   (pdCheque.PosBankAmount * poshdepexrate) as  dPdChequeSales,        
   (pdCheque.PosBankAmount * poshexchangerate) as cPdChequeSales        
  from                
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved          
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                          
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
--RefNo-2 ends --------------------------------------------        
*/                  
 union all                  
                   
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,             
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -                   
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -             
		 sum(isnull(idcostprice*idquantity,0)))) margin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from                   
   losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid     
   left outer join                   
   (select                  
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount                  
   from                  
    losInvoiceOC                   
   group by                  
   ioShopID,ioInvoiceID) ocd                   
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
   ashops s, adepartmentmaster d                   
  where                   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
 union all                  
                  
  select                   
   shopname, ihShopID, ihinvoicedate,                  
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) Cashsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,         
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,                   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,             
   0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -                   
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -             
		sum(isnull(idcostprice*idquantity,0)))) margin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from                   
   losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join                   
   (select                  
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount        
   from                  
    losInvoiceOC                   
   group by                  
   ioShopID,ioInvoiceID) ocd                   
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
   ashops s, adepartmentmaster d                   
  where                   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=1 and ihdepartmentid = d.departmentid and ihtype ='i'                  
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
                  
 union all                  
   select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehexchangerate)) ccashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
   0.0 creditsales,0.0 dcreditsales , 0.0 ccreditsales , sum(sedcostprice * sedquantity) costvalue,                  
   sum(sedcostprice * sedquantity) * sehdepexrate dcostvalue,                   
   sum(sedcostprice * sedquantity) * sehexchangerate ccostvalue,                  
   --convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedquantity) margin,  
   --convert(numeric(18,8), sum(sedunitprice* sehdepexrate)) -                   
   --sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   --convert(numeric(18,8), sum(sedunitprice * sehexchangerate )) -   
   --sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) - sum(sedcostprice * sedquantity) margin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) -                   
          sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) -   
          sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
    departmentname, sehdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d            
  where          
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange = 'E' and sehshopid = shopid and sehdepartmentid = d.departmentid          
  group by      
   shopname, sehshopid, departmentname, sehdepartmentid, sehexchangedate ,                  
   departmentname,sehdepexrate, sehexchangerate,sehExchangeID                  
 union all                  
       
 -- RefNo-4 start  commented below      
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  sum(idunitprice )) cashsales, convert(numeric(18,8),                   
 ------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,8),                   
 ------  sum(idunitprice * ihexchangerate)) ccashsales,                  
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  (convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                   
 ------  (convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                   
 ------  (convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin, departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  ihdepartmentid =d.departmentid and idratetype=0 and ihproforma=0 and                   
 ------  ihshopid = shopid and ihcashinvoice=1 and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, departmentname, ihdepartmentid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
 ------ union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                   
 ------  0.0 ccashsales, convert(numeric(18,8), sum(idunitprice )) creditsales,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate)) dcreditsales,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate)) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                  
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                  
 ------  convert(numeric(18,8), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate) - sum(idcostprice*reqqty) * ihexchangerate) cmargin,                   
 ------  departmentname, ihDepartmentId departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  idratetype=0 and ihproforma=0 and ihshopid = shopid and                   
 ------  ihcashinvoice=0 and ihDepartmentId = d.departmentid                  
 ------  and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname, ihinvoicedate ,                   
 ------  ihexchangerate, ihdepexrate,ihInvoiceid                  
                  
 ------union all                  
 -- RefNo-4 ends      
                  
  select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),-sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehexchangerate)) ccashsales,                  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(-sedcostprice * sedExchangeQty) costvalue,    --RefNo-3              
   sum(-sedcostprice * sedExchangeQty) * sehdepexrate dcostvalue, sum(-sedcostprice * sedExchangeQty)     --RefNo-3             
   * sehexchangerate ccostvalue,  
    ---(convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedExchangeQty)) margin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -                   
    --    sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -   
    --    sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
           sum(sedcostprice * sedExchangeQty)) margin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -                   
        sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
        sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
  
   departmentname, sehdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d                   
  where                   
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid                   
   and sehdepartmentid = d.departmentid                   
  group by                   
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,                  
   sehdepexrate,sedExchangeid                  
 union all       
       
 -- RefNo-4 start                  
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  -(sum(idunitprice ))) cashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihexchangerate))) ccashsales,                   
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(idcostprice * abs(reqqty)) costvalue,                   
 ------  sum(idcostprice * abs(reqqty)) * ihdepexrate dcostvalue, sum(idcostprice * abs(reqqty)) *                   
 ------  ihexchangerate ccostvalue,  -((convert(numeric(18,8), sum(idunitprice ))) -            
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0                    
 ------  and ihproforma=0 and ihshopid = shopid and ihTransfinished = 1                   
 ------  and ihcashinvoice=1 AND IDratetype=1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihdepartmentid, departmentname, ihshopid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
          
 ------union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice ))) creditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihdepexrate))) dcreditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihexchangerate))) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                   
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8),                   
 ------  sum(idunitprice ))) -  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                   
 ------  IHCANCELLED = 0 and ihproforma = 0 and ihshopid = shopid and                   
 ------  ihcashinvoice = 0 and idratetype = 1 and ihtransfinished = 1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname,                  
 ------  ihinvoicedate , ihexchangerate, ihdepexrate,ihInvoiceid                  
                  
 ------union all                  
      
-- special Invoice (cash)        
select         
shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccashsales,    
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales,   
  
0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty) margin,             
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,        
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty))* ihexchangerate cmargin,  
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                    
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all                                      
      
-------- special invoice - return before despatch                          
select shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,       
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-sum(idcostprice * reqqty) costvalue ,      
-sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
-sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
     
union all                                      
                                   
-- Special invoice return  - after desp                                    
select shopname,                                     
 ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,     
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                        
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1         
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
-- special Invoice (credit)      
union all      
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccreditsales,    
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
       
 sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice)))-sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))))-sum(idcostprice*reqqty) margin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                    
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice <>1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all         
      
-- special invoice - return before despatch                          
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,  
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,     
  
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
 -sum(idcostprice * reqqty) costvalue ,      
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) margin,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice <>1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                          
union all                                      
                                   
-- Special invoice return  - after desp                                    
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate))dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate))ccreditsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)dcreditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)ccreditsales,       
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
--idUnitPrice, idItemTaxAmount  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice <>1                                     
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
 -- RefNo-4 ends       
  union all                 
  select                   
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
   -- -convert(numeric(18,8), (sum(GRNDunitprice ))) creditsales,                   
   -- -convert(numeric(18,8), (sum(GRNDunitprice * grnhdepexRate))) dcreditsales,                   
   -- -convert(numeric(18,8), (sum(GRNDunitprice * grnhExchangeRate))) ccreditsales,   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) creditsales,                   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   
   -sum(grncostprice*grndquantity) costvalue, - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                   
   -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,                   
   -- -(convert(numeric(18,8), (sum(GRNDunitprice )))-sum(grncostprice*grndquantity)) margin,  
   -- -(convert(numeric(18,8), (sum(GRNDunitprice ))) -                   
   --    sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
   -- -(convert(numeric(18,8),(sum(GRNDunitprice ))) -  
   --     sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,                   
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))))-  
           sum(grncostprice*grndquantity)) margin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -                   
       sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -  
        sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,                   
   departmentname, grnhdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
    -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  from                   
   losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d                   
  where               
   GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0                   
   and grnhshopid = shopid and grnhdepartmentid = d.departmentid                   
  group by                   
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,                   
   grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID                  

  --hari added to include the service booking invoice parts replaced items                  
 UNION ALL                  
  
  --service invoice (cash)                
  select                   
   shopname, repinvdshopid, serinvhdate,  
   --convert(numeric(18,8),sum(repinvdrate* repinvdqty)) cashsales,  
   --convert(numeric(18,8),sum(repinvdrate* seinvhdepexrate * repinvdqty)) dcashsales,                  
   --convert(numeric(18,8),sum(repinvdrate* serinvhcmpexrate * repinvdqty)) ccashsales,                  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcashsales,            
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccashsales,            

   0.0 creditsales, 0.0 dcreditsales , 0.0 ccreditsales ,  sum(repinvdcostprice * repinvdqty) costvalue,                   
   sum(repinvdcostprice * repinvdqty) * seinvhdepexrate  dcostvalue,                   
   sum(repinvdcostprice * repinvdqty) *serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -  
   --  sum(repinvdcostprice * repinvdqty),                   
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,   
   --convert(numeric(18,8),(sum(repinvdrate  * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty)margin,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate dmargin,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate cmargin,            
  
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --RefNo-8  start commneted, since this gst amount is taken care in below
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
 --convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
   ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
--RefNo-8 ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d                   
  where                   
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1                  
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, serinvhDepartmentid,                   
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid                   
                  
 union all                  
 
  --service Details  (cash)                
  select                   
   shopname, serinvhshopid, serinvhdate,  
   --convert(numeric(18,8) , serinvhserviceamt) cashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccashsales ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate)dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate)ccashsales ,             
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                       
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,    
   
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)),             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) *  serinvhcmpexrate) ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate)dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate)ccashsales ,             

   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount  
  from                   
--RefNo-8 start commented below
   --losserviceinvheader, ashops s, adepartmentmaster d                   
	 --where                   
	 --  serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1                  
	 --  and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                  
   
  losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid   and Patindex('%y%',repinvdtype)>0 
 where                   
	serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1  
    and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends 
 union all
  
  --service invoice (credit)	    
    select                   
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , (sum(repinvdrate* repinvdqty))) creditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * seinvhdepexrate * repinvdqty))) dcreditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * serinvhcmpexrate * repinvdqty))) ccreditsales ,   
  
   convert(numeric(18,8),(sum( (repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
                     
   sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*                   
   seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty), convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty) * seinvhdepexrate , convert(numeric(18,8) ,                   
   --( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate ,                   
   
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * seinvhdepexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate,  
   
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  --RefNo-8  start commneted, since this gst amount is taken care in below
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
	 -- convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
	,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
  --RefNo-8  ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader,                   
   ashops s, adepartmentmaster d 
  where 
   serinvhid = repinvinvoiceid and                   
   serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is null                   
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid                    
   and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,                  
   serinvhcmpexrate ,serinvhid   
   
   union all
          
  --service Details   (credit)               
  select                   
   shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , serinvhserviceamt) creditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcreditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccreditsales ,     
   
   --RefNo-8 start commented below
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) creditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate) dcreditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate) ccreditsales ,             
   convert(numeric(18,8),serinvhserviceamt- (isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) creditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
   --RefNo-8 ends
   
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*seinvhdepexrate) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*serinvhcmpexrate) ,             
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount    
  from                   
  --RefNo-8 start commented below
  -- losserviceinvheader, ashops s, adepartmentmaster d                   
  --where                   
  -- serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                   
  losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0 
 where                   
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends
   
  union all                  


  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002                  
  --credit           
  select           
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,                   
   0.0 ccashsales,                  
    convert(numeric(18,8), sum(redunitprice)) creditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehdepexrate)  dcreditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehexchangerate) ccreditsales,
   sum(redcostprice * redquantity) costvalue,                   
   sum(redcostprice * redquantity) * rehdepexrate dcostvalue, 
   sum(redcostprice * redquantity) * rehexchangerate ccostvalue,
   (convert(numeric(18,8), sum(redunitprice ))) -  sum(redcostprice * redquantity) margin,
   (convert(numeric(18,8), sum(redunitprice * rehdepexrate))) -                   
		sum(redcostprice * redquantity) * rehdepexrate dmargin,
   (convert(numeric(18,8), sum(redunitprice * rehexchangerate))) - 
		sum(redcostprice * redquantity) * rehexchangerate cmargin,                   
   departmentname, rehdepartmentid                  
 ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,0,0,0  
  from                   
   losExportDetail, losExportHeader, ashops s, adepartmentmaster d                   
  where                   
   rehExportID = redExportID and rehshopid = redshopid AND                   
   reHCANCELLED=0 and rehtype ='i' and                  
   rehproforma=0 and rehshopid = shopid and rehcashinvoice=0 and                   
   rehdepartmentid = d.departmentid                   
  group by                   
   shopname, rehshopid, departmentname, rehdepartmentid, rehExportDate,                   
   rehdepexrate, rehexchangerate,rehExportID                   
            
 union all                  
 -- added From Vwcashsales -Margin Not calculating                  
                   
 select                   
  s.shopname, vws.sishopid, vws.siinvoicedate,                   
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,                   
  convert(numeric(18,8),sum(vws.sidamount)) as  dcashsales,  -- RefNo-7 corrected amount                  
  convert(numeric(18,8),sum(vws.sicamount)) as ccashsales,   -- RefNo-7 corrected amount                                  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
   0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
  convert(numeric(18,8),sum(vws.siamount))as margin,    -- RefNo-7 included  -vws.GSTAmount                              
  convert(numeric(18,8),sum(vws.sidamount))as  dmargin,    -- RefNo-7 included  -vws.GSTAmount                               
  convert(numeric(18,8),sum(vws.sicamount))as cmargin,  -- RefNo-7 included  -vws.GSTAmount                              
  d.departmentname,lah.aidepartmentid  departmentid                   
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
  , sum(vws.dGSTAmount)as dGSTAmount  
  , sum(vws.cGSTAmount)as cGSTAmount  
 from                   
  vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d ,ashops s                  
 where                   
  aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
  aishopid = sishopid and lah.aicashinvoice=1 and                   
  lah.aidepartmentid =d.departmentid and s.departmentid = d.departmentid                  
  and aiShopId = s.ShopId                  
 group by                   
  s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid, vws.siinvoicedate                  
  ,aidepexrate, aiexchangerate               
 union all                  
                  
    select s.shopname, vws.sishopid, vws.siinvoicedate,                   
    0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
    convert(numeric(18,8),sum(vws.siamount))as creditsales,                   
    convert(numeric(18,8),sum(vws.sidamount))as dcreditsales, -- RefNo-7 corrected amount                   
    convert(numeric(18,8),sum(vws.sidamount))as ccreditsales, -- RefNo-7 corrected amount                                    
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
    convert(numeric(18,8),sum(vws.siamount)) as margin,    -- RefNo-7 included  -vws.GSTAmount              
    convert(numeric(18,8),sum(vws.sidamount)) as dmargin,  -- RefNo-7 included  -vws.GSTAmount               
    convert(numeric(18,8),sum(vws.sicamount)) as cmargin,  -- RefNo-7 included  -vws.GSTAmount                    
    d.departmentname,lah.aidepartmentid  departmentid                   
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
    , sum(vws.dGSTAmount)as dGSTAmount  
    , sum(vws.cGSTAmount)as cGSTAmount  
    from vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d,ashops s      
    where aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
    aishopid = sishopid and lah.aicashinvoice=0 and lah.aidepartmentid =d.departmentid                  
    and s.departmentid = d.departmentid and s.ShopId = aiShopId group by                       
    s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid,vws.siinvoicedate,aiinvoiceid,
    aidepexrate                   
                   
    UniOn All -- added from vwCashSales                 
    --Shop debit credit notes and handling debit notes which are debit to the                
    -- customer and hence act as invoices to be settled                      
    Select  s.shopname,losdcnshopid,losdcndate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
    COnvert(numeric(18,8),Sum(losDCNAmount))  creditsales,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dcreditsales,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  ccreditsales,               
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    COnvert(numeric(18,8),Sum(losDCNAmount))  margin,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dmargin,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  cmargin,              
 d.departmentname,losdcndepartmentid                   
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2    
       ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount      
    From Ashops s,  losdebitcreditnote, adepartmentmaster d               
    Where  s.shopid = losdcnshopid And s.accountable Is Not Null                   
    And d.DepartmentID = losdcndepartmentid And losdcncancelled =0                    
    And losdcndebit =1  Group By s.shopname,d.departmentname,losdcnshopid,                  
    losdcndate, losdepexrate, losexchangerate,losdcndepartmentid              
              
    --hq serivce invoice dOne for shop                    
    Union all              
               
    Select  null, 0,ai.invoicedate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  creditsales,                     
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dcreditsales,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  ccreditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)ccreditsales,         
  
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  margin,                     
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dmargin,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  cmargin,   
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)) * exchangerate)cmargin,        
                 
    d.departmentname,ai.departmentid           
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
     ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount   
     ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,  
      convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount  
  
  From accountsinvoiceheader ai, serviceinvoicedetails ser ,adepartmentmaster d              
    Where ai.invoiceid = ser.invoiceid And ai.companyid =                     
    ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0             
    and ai.departmentid = d.departmentid and ai.companyid = d.companyid               
    Group By  ai.invoicedate,depexrate,exchangerate,              
    d.departmentname,ai.departmentid              
        
  
 ----F&B---------------------------   
 --RefNo-5----------------------------------------------start----------------------------------------------------------------------------  
 ----------------------------------------  
 -- select v.* from        
 --(        
--select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales,        
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 --inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 --UNION ALL        
        
 --select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales,        
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 --inner join aitem a on a.itemid=fb_pd_dishid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 --where fb_pd_AddedItemtype=2        
 --)v       
  
/*  
union all  
  select shopname,poshShopID,poshBillDate,Cashsales,DepCashsales,ComCashsales,Creditsales,DepCreditsales,  
 ComCreditsales,costprice,dcostprice,ccostprice,margin,dmargin,cmargin,deptname,deptid,  
PdChequeSales,dPdChequeSales,cPdChequeSales  from  
 (        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid) costprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2        
  fb_pd_processdetailid  
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 UNION ALL        
        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2   
  fb_pd_processdetailid       
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 inner join aitem a on a.itemid=fb_pd_dishid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 where fb_pd_AddedItemtype=2        
  
  
 )  
  
  v        
 --RefNo-5----------------------------------------------end----------------------------------------------------------------------------  
  ----------------------------------------                  
  */  
     
 )cashcreditcollection      
group by                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid,                   
 cashcreditcollection.poshbilldate   
  
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwHPinvoices')
   DROP view dbo.vwHPinvoices
GO
/*        
 Created by :  Shinu        
 Created on : 12/12/2007          
 Modified by :         
 Modified on :          
 Purpose      : To Get all the hire purchase Receivables of customers          
 */        
 ------------------------------------------------------------------------
 --Ref.No-1
 --Modified Date:14/07/2012
 --Modified By  : AADYAKUMAR.D.V
 --Reason       : When i am checking i had found another table column is used for Posting.
 --             : So i had modified this view to compare it with General Ledger value
 ------------------------------------------------------------------------  
create VIEW vwHPinvoices as           
-- 1 Invoices         
SELECT           
 LIH.hpqhCompanyID CompanyID,hpqhshopid ShopID, a.DepartmentID, LIH.hpqhQuotationID InvoiceID, LIH.hpqhcustomerid CustomerID,           
 LIH.hpqhQuotationDate InvoiceDate, LIH.hpqhQuotationNo InvoiceNO,''ReferenceNO, LIH.hpqhremarks Remarks,          
 --Ref.No-1---START---
 --hpqhinstprice as InvAmt ,
 case when hpqdActInstallmentPrice is null then hpqhinstprice else hpqdActInstallmentPrice end InvAmt,
 --Ref.No-1----END----
 '0 - 30' as Due,           
 'HPI' AS Type ,'HP Trade Debtors' Debtortype,LIH.hpqhupdatetime UpdateTime,CustomerCategory,'' DueDate,1 DepExrate,        
 7504 InterfaceID,0 SalePersonID, '' CustomerType,  0 DutyAmt,0 CostPrice      
FROM           
 (select ad.DepartmentID,ShopID  from aDepartmentMaster ad,ASHOPS ash WHERE ash.DepartmentID=AD.DepartmentID)a        
 ,acustomermaster c, loshpInvoiceheader  LIH          
 Left outer join loshpInvoiceDetail  LID           
 on LIH.hpqhQuotationID = LID.hpqdQuotationID and LIH.hpqhCompanyID = LID.hpqdCompanyID
 left outer join losHpInvoiceDetailOthers HID on HID.hpqdShopId = hpqhshopid and HID.hpqdQuotationId  = hpqhQuotationID                  
WHERE           
 c.customerid = LIH.hpqhcustomerid and          
 LIH.hpqhCancel = 0 and (datediff(dd,LIH.hpqhQuotationDate,getdate())  between 0 and 30)          
 and a.ShopID= hpqhshopid and hpqhType='I' and hpqhConfirmed=1         
group by           
 LIH.hpqhCompanyID, hpqhshopid, a.DepartmentID, LIH.hpqhQuotationID, LIH.hpqhcustomerid,           
 LIH.hpqhQuotationDate, LIH.hpqhQuotationNo, LIH.hpqhremarks,          
 hpqhinstprice,LIH.hpqhupdatetime,c.CustomerCategory 
 ,hpqdActInstallmentPrice         
          
UNION ALL          
          
SELECT           
 LIH.hpqhCompanyID, hpqhshopid, a.DepartmentID, LIH.hpqhQuotationID, LIH.hpqhcustomerid,           
 LIH.hpqhQuotationDate, LIH.hpqhQuotationNo,'', LIH.hpqhremarks,   
 --Ref.No-1---START---       
 --hpqhinstprice as InvAmt ,
 case when hpqdActInstallmentPrice is null then hpqhinstprice else hpqdActInstallmentPrice end InvAmt,
  --Ref.No-1----END----
 '31 - 60' as Due,           
 'HPI' AS Type ,'HP Trade Debtors' Debtortype,LIH.hpqhupdatetime,CustomerCategory,'',1,        
 7504 InterFaceID ,0,'',0,0        
FROM           
 (select ad.DepartmentID,ShopID  from aDepartmentMaster ad,ASHOPS ash WHERE ash.DepartmentID=AD.DepartmentID)a        
 ,acustomermaster c, loshpInvoiceheader  LIH          
 Left outer join loshpInvoiceDetail  LID           
 on LIH.hpqhQuotationID = LID.hpqdQuotationID and LIH.hpqhCompanyID = LID.hpqdCompanyID 
 left outer join losHpInvoiceDetailOthers HID on HID.hpqdShopId = hpqhshopid and HID.hpqdQuotationId  = hpqhQuotationID                
WHERE           
 c.customerid = LIH.hpqhcustomerid and          
 LIH.hpqhCancel = 0 and (datediff(dd,LIH.hpqhQuotationDate,getdate())  between 31 and 60)          
 and a.ShopID= hpqhshopid and hpqhType='I' and hpqhConfirmed=1        
group by           
 LIH.hpqhCompanyID, hpqhshopid, a.DepartmentID, LIH.hpqhQuotationID, LIH.hpqhcustomerid,           
 LIH.hpqhQuotationDate, LIH.hpqhQuotationNo, LIH.hpqhremarks,          
 hpqhinstprice,LIH.hpqhupdatetime,CustomerCategory          
 ,hpqdActInstallmentPrice       
union all          
          
SELECT           
 LIH.hpqhCompanyID, hpqhshopid, a.DepartmentID, LIH.hpqhQuotationID, LIH.hpqhcustomerid,           
 LIH.hpqhQuotationDate, LIH.hpqhQuotationNo,'', LIH.hpqhremarks,
 --Ref.No-1---START---          
 --hpqhinstprice as InvAmt ,
 case when hpqdActInstallmentPrice is null then hpqhinstprice else hpqdActInstallmentPrice end InvAmt,
 --Ref.No-1----END----
 '61 - 90' as Due,           
 'HPI' AS Type ,'HP Trade Debtors' Debtortype,LIH.hpqhupdatetime,CustomerCategory,'',1,          
 7504 InterFaceID,0,'',0,0           
FROM           
 (select ad.DepartmentID,ShopID  from aDepartmentMaster ad,ASHOPS ash WHERE ash.DepartmentID=AD.DepartmentID)a        
 ,acustomermaster c, loshpInvoiceheader  LIH          
 Left outer join loshpInvoiceDetail  LID           
 on LIH.hpqhQuotationID = LID.hpqdQuotationID and LIH.hpqhCompanyID = LID.hpqdCompanyID           
 left outer join losHpInvoiceDetailOthers HID on HID.hpqdShopId = hpqhshopid and HID.hpqdQuotationId  = hpqhQuotationID           
WHERE           
 c.customerid = LIH.hpqhcustomerid and          
 LIH.hpqhCancel = 0 and (datediff(dd,LIH.hpqhQuotationDate,getdate())  between 61 and 90)          
 and a.ShopID= hpqhshopid and hpqhType='I'  and hpqhConfirmed=1       
group by           
 LIH.hpqhCompanyID, hpqhshopid, a.DepartmentID, LIH.hpqhQuotationID, LIH.hpqhcustomerid,           
 LIH.hpqhQuotationDate, LIH.hpqhQuotationNo, LIH.hpqhremarks,          
 hpqhinstprice,LIH.hpqhupdatetime,CustomerCategory             
 ,hpqdActInstallmentPrice          
union all          
         
SELECT           
 LIH.hpqhCompanyID, hpqhshopid, a.DepartmentID, LIH.hpqhQuotationID, LIH.hpqhcustomerid,           
 LIH.hpqhQuotationDate, LIH.hpqhQuotationNo,'', LIH.hpqhremarks,   
 --Ref.No-1---START---         
 --hpqhinstprice as InvAmt ,
 case when hpqdActInstallmentPrice is null then hpqhinstprice else hpqdActInstallmentPrice end InvAmt,
 --Ref.No-1----END----
 '>90' as Due,           
 'HPI' AS Type ,'HP Trade Debtors' Debtortype,LIH.hpqhupdatetime,CustomerCategory,'',1,          
 7504 InterFaceID ,0,'',0,0          
FROM           
 (select ad.DepartmentID,ShopID  from aDepartmentMaster ad,ASHOPS ash WHERE ash.DepartmentID=AD.DepartmentID)a        
 ,acustomermaster c, loshpInvoiceheader  LIH          
 Left outer join loshpInvoiceDetail  LID           
 on LIH.hpqhQuotationID = LID.hpqdQuotationID and LIH.hpqhCompanyID = LID.hpqdCompanyID
 left outer join losHpInvoiceDetailOthers HID on HID.hpqdShopId = hpqhshopid and HID.hpqdQuotationId  = hpqhQuotationID           
WHERE           
 c.customerid = LIH.hpqhcustomerid and          
 LIH.hpqhCancel = 0 and (datediff(dd,LIH.hpqhQuotationDate,getdate()) >90)          
 and a.ShopID= hpqhshopid and hpqhType='I' and hpqhConfirmed=1        
group by           
 LIH.hpqhCompanyID, hpqhshopid, a.DepartmentID, LIH.hpqhQuotationID, LIH.hpqhcustomerid,           
 LIH.hpqhQuotationDate, LIH.hpqhQuotationNo, LIH.hpqhremarks,          
 hpqhinstprice,LIH.hpqhupdatetime,CustomerCategory             
 ,hpqdActInstallmentPrice       
-- 2 Payments        
UNION ALL        
        
SELECT        
 ph.hphCompanyID, 0, hphDepartmentID, hphPaymentID, hphcustomerid,           
 hphPaymentDate, hphPaymentNo,'', hphRemarks,          
 (hphPaymentAmount/hphBankExchangeRate)*hphCusExchangeRate ,'0 - 30' as Due,           
 'HPP' AS Type ,'HP Trade Debtors' Debtortype,hphupdatetime,CustomerCategory,'',1,          
 7511 InterFaceID ,0,'',0,0          
FROM    acustomermaster c, ahppaymentHeader  ph        
 Left outer join ahppaymentDetail  pd        
 on hphPaymentID = hpdPaymentID and hphCompanyID = hpdCompanyID           
WHERE           
 c.customerid = hphcustomerid and          
 hphCancel = 0 and (datediff(dd,hphPaymentDate,getdate())  between 0 and 30)         
group by           
 hphCompanyID,hphDepartmentID,hphPaymentID, hphcustomerid,           
 hphPaymentDate, hphPaymentNo, hphRemarks,          
 (hphPaymentAmount/hphBankExchangeRate)*hphCusExchangeRate,hphupdatetime ,CustomerCategory            
        
UNION ALL        
        
SELECT        
 ph.hphCompanyID, 0, hphDepartmentID, hphPaymentID, hphcustomerid,           
 hphPaymentDate, hphPaymentNo,'', hphRemarks,          
 (hphPaymentAmount/hphBankExchangeRate)*hphCusExchangeRate ,'31 - 60' as Due,           
 'HPP' AS Type ,'HP Trade Debtors' Debtortype,hphupdatetime,CustomerCategory,'',1,          
 7511 InterFaceID,0,'',0,0           
FROM    acustomermaster c, ahppaymentHeader  ph        
 Left outer join ahppaymentDetail  pd        
 on hphPaymentID = hpdPaymentID and hphCompanyID = hpdCompanyID           
WHERE           
 c.customerid = hphcustomerid and          
 hphCancel = 0 and (datediff(dd,hphPaymentDate,getdate())  between 31 and 60)         
group by           
 hphCompanyID,hphDepartmentID,hphPaymentID, hphcustomerid,           
 hphPaymentDate, hphPaymentNo, hphRemarks,          
 (hphPaymentAmount/hphBankExchangeRate)*hphCusExchangeRate,hphupdatetime,CustomerCategory             
UNION ALL        
        
SELECT        
 ph.hphCompanyID, 0, hphDepartmentID, hphPaymentID, hphcustomerid,           
 hphPaymentDate, hphPaymentNo,'', hphRemarks,          
 (hphPaymentAmount/hphBankExchangeRate)*hphCusExchangeRate ,'61 - 90' as Due,           
 'HPP' AS Type ,'HP Trade Debtors' Debtortype,hphupdatetime, CustomerCategory,'',1,         
 7511 InterFaceID ,0,'',0,0          
FROM    acustomermaster c, ahppaymentHeader  ph        
 Left outer join ahppaymentDetail  pd        
 on hphPaymentID = hpdPaymentID and hphCompanyID = hpdCompanyID           
WHERE           
 c.customerid = hphcustomerid and          
 hphCancel = 0 and (datediff(dd,hphPaymentDate,getdate())  between 61 and 90)         
group by           
 hphCompanyID,hphDepartmentID,hphPaymentID, hphcustomerid,           
 hphPaymentDate, hphPaymentNo, hphRemarks,          
 (hphPaymentAmount/hphBankExchangeRate)*hphCusExchangeRate,hphupdatetime,CustomerCategory             
UNION ALL        
        
SELECT        
 ph.hphCompanyID, 0, hphDepartmentID, hphPaymentID, hphcustomerid,           
 hphPaymentDate, hphPaymentNo,'', hphRemarks,          
 (hphPaymentAmount/hphBankExchangeRate)*hphCusExchangeRate  ,'>90' as Due,           
 'HPP' AS Type ,'HP Trade Debtors' Debtortype,hphupdatetime,CustomerCategory,'',1,          
 7511 InterFaceID ,0,'',0,0          
FROM    acustomermaster c, ahppaymentHeader  ph        
 Left outer join ahppaymentDetail  pd        
 on hphPaymentID = hpdPaymentID and hphCompanyID = hpdCompanyID           
WHERE           
 c.customerid = hphcustomerid and          
 hphCancel = 0 and (datediff(dd,hphPaymentDate,getdate()) >90)         
group by           
 hphCompanyID,hphDepartmentID,hphPaymentID, hphcustomerid,           
 hphPaymentDate, hphPaymentNo, hphRemarks,          
 (hphPaymentAmount/hphBankExchangeRate)*hphCusExchangeRate,hphupdatetime,CustomerCategory            
         

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

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwCustomerSales')
   DROP view dbo.vwCustomerSales
GO
          
-- Modified on   : 05/09/2004                      
-- Modified by  : Hariharan,Sebin                       
-- CommentS             : Added details for rexporting to customers                      
--   : Separated Exchange in and exchange out into 2 queries                      
--                      : Changed the linking with losposHeader to country master and                       
--                      : currency master into left outer join. In pos and Exchange.                      
--   : Added columns for depsalesamt and cmpsalesamt, added referenceno                      
--   : Other charges changes                      
--   : specialinvoice chking transfinished, transfinished checking given for special invoice which were missed earlier                      
--    : added goods return also on venkitesh 150404                      
--   : Other charges given in group by clause to avoid doubling in Invoice queries               
--   : Updated the shop credit special invoice               
--   :--jyothish changed -ve to depsales and cmpsalses  on exchange in(151209)          
--select * from vwCustomerSales where ihshopid=6 and Year(ihinvoiceDate)=2009 and Month(ihinvoiceDate)>=05             
-----------------------------        
--RefNo:01        
--Modified : VinothMurugan V         
--Purpose  : changed -ve to depsales and cmpsalses          
-----------------------------          
-----------------------    
--RefNo   : 02    
--Date   : 20/09/2010    
--Modified By : VinothMurugan V.    
--Purpose  : Adding Item category this one is missed in standard db.Now i added compared with simdi db.    
--Ticket--SXJ-583458    
    
------------------------      
--RefNo    : 03        
--Modified : Aadyakumar.D.V  
--Purpose  : For "rptsalesregister" all are requsted to use vwSalesRegister.  
--         : This view is modified as per reference 01 and 02 so new view is created.  
-----------------------------          
--RefNo-04 
--Modified : Bijesh. B
--Date     : 27/07/2012
--Client   : Sonee
--Purpose  : Included Service Modlue
-----------------------------          
          
create VIEW dbo.vwCustomerSales AS                      
--1. shop cash sales invoice                      
select                       
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcashaccid,                       
 convert(numeric(18,2), sum(isnull(invd.idunitprice,0)+isnull(ocd.ioAmount,0))) as amount,                       
 1 as cashsales, 'c' as transtype, ihCustomerId, ihdepartmentid,                       
 convert(numeric(18, 2), sum(isnull(idcostprice * invd.idquantity,0))) camt,                       
 convert(numeric(18, 2), sum(isnull(idcostprice * invd.idquantity,0)) * ihDepExRate) DepAmount,                      
 convert(numeric(18, 2), sum(isnull(idcostprice * invd.idquantity,0)) * ihExchangeRate) CmpAmount,                      
 countryname, ihinvoiceno,                       
 convert(numeric(18, 2), sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) -                       
 convert(numeric(18, 2), sum(isnull(idcostprice * invd.idquantity,0))) profit,                       
 convert(numeric(18, 2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihDepExRate) -                       
 convert(numeric(18, 2), sum(isnull((idcostprice * invd.idquantity),0)) * ihDepExRate) as DepProfit,                      
 convert(numeric(18, 2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihExchangeRate) -                       
 convert(numeric(18, 2), sum(isnull(idcostprice * invd.idquantity,0)) * ihExchangeRate) as CmpProfit,CustomerCardNo ,                        
 convert(numeric(18, 2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihDepExRate) DepSalesAmt,                       
 convert(numeric(18, 2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihExchangeRate) CmpSalesAmt,                       
 Customername, ihReferenceNo,    
ic.ItemCategoryID, CategoryNameDescription  --RefNo: 02                     
from            
 losinvoiceheader ih                       
 left outer join losinvoicedetail invd                      
 on ih.ihshopid = invd.idshopid and ih.ihinvoiceid = invd.idinvoiceid      
-------------------------------------------RefNo: 02    
 left outer join aitem i on  invd.idItemID=i.ItemID      
 left outer join aitemcategory ic on i.ItemCategoryID=ic.ItemCategoryID      
-----------------------------------------                     
 left outer join                       
 (select                   
  ioShopID,ioInvoiceID,sum(ioAmount) ioAmount                      
 from                      
  losInvoiceOC                       
 group by                      
  ioShopID,ioInvoiceID) ocd                       
 on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                       
 acustomermaster c, acountrymaster cm                       
where                       
 ihcancelled=0 and ihproforma = 0 and ihcashinvoice =1 and                       
 ihcustomerid=c.customerid and c.countryid = cm.countryid and ihtype ='i'                       
group by                       
 ihcompanyid, ihshopid, ihinvoiceno, ihinvoicedate, ihinvoiceid, ihbankcashaccid,                       
 ihexchangerate,ihCustomerId ,ihdepartmentid, countryname,                       
 CustomerCardNo, Customername, ihReferenceNo, ocd.ioAmount, ihExchangeRate, ihDepExRate,    
ic.CategoryNameDescription,ic.ItemCategoryID   ----RefNo: 02                      
                      
union all                       
                      
-- 2.shop cash sales special invoice                      
                      
select                       
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcashaccid,                       
 convert(numeric(18, 2), sum(vw.idunitprice) )  as amount, 1,                       
 'd' as transtype, ihCustomerID, ihdepartmentid,                       
 convert(numeric(18, 2), sum(vw.costprice * invd.idquantity)) camt,                       
 convert(numeric(18, 2), sum(vw.costprice * invd.idquantity) * ih.ihdepexRate) DepAmt,                    
 convert(numeric(18, 2), sum(vw.costprice * invd.idquantity) * ih.ihExchangeRate) CmpAmt,                      
 countryname, ihinvoiceno,                       
 convert(numeric(18, 2), sum(vw.idunitprice)) -                       
 convert(numeric(18, 2), sum(vw.costprice * invd.idquantity)) Profit,                      
 convert(numeric(18, 2), sum(vw.idunitprice) * ih.ihDepExRate) -                       
 convert(numeric(18, 2), sum(vw.costprice * invd.idquantity) * ih.ihDepExRate) DepProfit,                       
 convert(numeric(18, 2), sum(vw.idunitprice) * ih.ihExchangeRate) -                       
 convert(numeric(18, 2), sum(vw.costprice * invd.idquantity) * ihExchangeRate) Cmpprofit,                      
 CustomerCardNo , convert(numeric(18, 2),sum(vw.idunitprice) * ihDepExrate) DepSalesAmt,                       
 convert(numeric(18, 2),sum(vw.idunitprice) * ihExchangeRate) CmpSalesAmt, CustomerName, ihReferenceNo,    
ic.ItemCategoryID, CategoryNameDescription ----RefNo: 02                      
from                       
 losspecialinvoiceheader ih, losspecialinvoicedetail invd, vwShopSplInvItemAmount vw,                       
 acustomermaster c, acountrymaster cm ,    
aitemcategory ic,aitem i ----RefNo: 02                      
where                       
 vw.idshopid = invd.idshopid and vw.idinvoiceid = invd.idinvoiceid and                       
 vw.iditemid = invd.iditemid and ih.ihshopid = invd.idshopid and                       
 ih.ihinvoiceid = invd.idinvoiceid and ihcancelled = 0 and ihproforma = 0 and                       
 ihcashinvoice = 1 and invd.idratetype = 0 and ihcustomerid = c.customerid and                       
 c.countryid = cm.countryid  and ih.ihtransfinished=1      
-------------------RefNo: 02    
and i.ItemID=invd.idItemid      
 and ic.ItemCategoryID=i.ItemCategoryID            
-----------------                    
group by                       
 ihcompanyid, ihshopid, ihinvoiceno, ihinvoicedate, ihinvoiceid, ihbankcashaccid,                       
 ihexchangerate, ihCustomerID, ihdepartmentid, countryname , CustomerCardNo,                       
 Customername, ihReferenceNo, ihDepExRate ,    
ic.ItemCategoryID, ic.CategoryNameDescription ----RefNo: 02                     
                      
union all                      
                      
-- 3. shop cash service invoice                      
select                       
 vws.sicompanyid, vws.sishopid, vws.siinvoicedate, lah.aibankcashid,                       
 convert(numeric(18,2),vws.siamount ) as amount , lah.aicashinvoice, 's' as transtype,                       
 lah.aiCustomerid, aidepartmentid, 0.0 cAmt, 0.0 DepAmount, 0.0 cmpAmount,countryname,                       
 lah.aiinvoiceno, convert(numeric(18, 2), vws.siamount) profit,                      
 convert(numeric(18, 2), vws.siamount) * lah.aiDepExRate  DepProfit,                      
 convert(numeric(18, 2), vws.siamount) * lah.aiExchangeRate CmpProfit,                      
 CustomerCardNo, convert(numeric(18,2), vws.siamount * lah.aiDepExRate ) depsalesamt,                       
 convert(numeric(18,2), vws.siamount * lah.aiExchangeRate) cmpSalesAmt, CustomerName, aiReferenceno,    
null,null ----RefNo: 02                      
from                       
 vwshopservicesales vws , LOsAccountsInvoiceHeader lah, acustomermaster c,                       
 acountrymaster cm                      
where                       
 aiinvoiceid=siinvoiceid and aicancelled=0 and aicustomerid = c.customerid and                       
 c.countryid = cm.countryid and aiproforma=0 and aishopid = sishopid and                       
 lah.aicashinvoice =1                       
                      
union all                       
                      
-- 4. hq cash service invoice                      
select                       
 ah.companyid, null, ah.invoicedate, ah.bankcashid,                       
 convert(numeric(18,2),sum(serviceqty * amount) ) as amount , 1 , 'as' as transtype,                       
ah.Customerid,ah.departmentid, 0 camt, 0 DepAmount, 0 CmpAmount, countryname,                       
 ah.invoiceno, convert(numeric(18,2),sum(serviceqty * amount) ) profit,                       
 convert(numeric(18,2),sum(serviceqty * amount) * ah.depExRate) DepProfit,                       
 convert(numeric(18,2),sum(serviceqty * amount) * ah.ExchangeRate) CmpProfit,                       
 CustomerCardNo, convert(numeric(18,2),sum(serviceqty * amount) * ah.depExRate)  depsalesamt,                       
 convert(numeric(18,2),sum(serviceqty * amount * ah.ExchangeRate))  cmpsalesamt,                       
 CustomerName, Referenceno,    
null,null----RefNo: 02                      
from                       
 serviceinvoicedetails sd, AccountsInvoiceHeader ah, acustomermaster c,                       
 acountrymaster cm                       
where                       
 ah.invoiceid = sd.invoiceid and ah.companyid = sd.companyid and ah.cancelled = 0 and                       
 ah.proforma=0 and ah.cashinvoice = 1 and ah.customerid = c.customerid and                       
 c.countryid = cm.countryid                  
group by                       
 ah.companyid, ah.invoicedate, ah.bankcashid,ah.exchangerate, ah.customerid,                      
 ah.departmentid, countryname, invoiceno, CustomerCardNo, Customername,                       
 Referenceno, ah.depExRate                      
                      
union all                       
                      
---- 5. shop credit sales invoice                      
select                       
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcashaccid,                       
 convert(numeric(18,2), sum(isnull(invd.idunitprice,0))+isnull(ocd.ioAmount,0)) as amount,                       
 0 as cashsales, 'c' as transtype, ihCustomerId, ihdepartmentid,                       
 convert(numeric(18, 2), sum(isnull(idcostprice * invd.idquantity,0))) camt,                       
 convert(numeric(18, 2), sum(isnull(idcostprice * invd.idquantity,0)) * ihDepExRate) DepAmount,   
 convert(numeric(18, 2), sum(isnull(idcostprice * invd.idquantity,0)) * ihExchangeRate) CmpAmount,                      
 countryname, ihinvoiceno,                       
 convert(numeric(18, 2), sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) -                       
 convert(numeric(18, 2), sum(isnull(idcostprice * invd.idquantity,0))) profit,                       
 convert(numeric(18, 2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihDepExRate) -                       
 convert(numeric(18, 2), sum(isnull((idcostprice * invd.idquantity),0)) * ihDepExRate) as DepProfit,           
 convert(numeric(18, 2), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihExchangeRate) -                       
 convert(numeric(18, 2), sum(isnull(idcostprice * invd.idquantity,0)) * ihExchangeRate) as CmpProfit,CustomerCardNo ,                        
 convert(numeric(18, 2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihDepExRate) DepSalesAmt,                       
 convert(numeric(18, 2), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihExchangeRate) CmpSalesAmt,                       
 Customername, ihReferenceNo,    
 ic.ItemCategoryID, CategoryNameDescription  ----RefNo: 02                      
from                       
 losinvoiceheader ih                       
 left outer join losinvoicedetail invd                      
 on ih.ihshopid = invd.idshopid and ih.ihinvoiceid = invd.idinvoiceid     
------------------------------------RefNo: 02    
left outer join aitem i on  invd.idItemID=i.ItemID      
 left outer join aitemcategory ic on i.ItemCategoryID=ic.ItemCategoryID    
----------------------------------                      
 left outer join                       
 (select                      
  ioShopID,ioInvoiceID,sum(ioAmount) ioAmount                      
 from                      
  losInvoiceOC                       
 group by                      
  ioShopID,ioInvoiceID) ocd                       
 on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                       
 acustomermaster c, acountrymaster cm                       
where                       
 ihcancelled=0 and ihproforma = 0 and ihcashinvoice =0 and                    
 ihcustomerid=c.customerid and c.countryid = cm.countryid and ihtype ='i'                       
group by                       
 ihcompanyid, ihshopid, ihinvoiceno, ihinvoicedate, ihinvoiceid, ihbankcashaccid,                       
 ihexchangerate,ihCustomerId ,ihdepartmentid, countryname,                       
 CustomerCardNo, Customername, ihReferenceNo, ocd.ioAmount, ihDepExRate,    
 ic.ItemCategoryID, CategoryNameDescription  ----RefNo: 02                     
                      
union all                      
-- 6. shop credit special invoice                      
select                       
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcashaccid,                       
 convert(numeric(18,2),sum(vw.idunitprice) ) amount,                       
 0 ihcashinvoice, 'd' as transtype, ihCustomerId, ihdepartmentid,                       
 convert(numeric(18, 2), sum(vw.costprice * invd.idquantity)) camt,                       
 convert(numeric(18, 2), sum(vw.costprice * invd.idquantity) * ihDepExRate) DepAmount,                      
 convert(numeric(18, 2), sum(vw.costprice * invd.idquantity) * ihExchangeRate) CmpAmount,                      
 countryname, ihinvoiceno,             
 case when ihNoofOCDetails > 0                     
 then -convert(numeric(18, 2), Abs(sum(vw.idunitprice)) - sum(idcostprice * invd.idquantity))             
 else convert(numeric(18, 2), Abs(sum(vw.idunitprice)) - sum(idcostprice * invd.idquantity)) end profit,            
 case when ihNoofOCDetails > 0                       
 then -convert(numeric(18, 2), Abs(sum(vw.idunitprice * ihDepExRate)) - sum(idcostprice * invd.idquantity) * ihDepExRate)             
 else convert(numeric(18, 2), Abs(sum(vw.idunitprice * ihDepExRate)) - sum(idcostprice * invd.idquantity) * ihDepExRate) end DepProfit,               
 case when ihNoofOCDetails > 0                     
 then -convert(numeric(18, 2), Abs(sum(vw.idunitprice * ihExchangeRate)) - sum(idcostprice * invd.idquantity) * ihExchangeRate)            
 else convert(numeric(18, 2), Abs(sum(vw.idunitprice * ihExchangeRate)) - sum(idcostprice * invd.idquantity) * ihExchangeRate) end CmpProfit,                      
 customercardno , convert(numeric(18,2),sum(vw.idunitprice)* ihDepExRate) as depsalesamt,                       
 convert(numeric(18,2),sum(vw.idunitprice* ihExchangerate) ) as cmpSalesamt, CustomerName, ihReferenceNo,    
ic.ItemCategoryID,CategoryNameDescription ----RefNo: 02                      
from                       
 losspecialinvoiceheader ih, (select idinvoiceID,idShopId,iditemid,idRateType,sum(idquantity)idquantity,idCostPrice               
  from losspecialinvoicedetail group by idinvoiceID,idShopId,iditemid,idRateType,idCostPrice)  invd    
------------------------------------RefNo: 02    
 left outer join aitem i on  invd.iditemid=i.ItemID      
 left outer join aitemcategory ic on i.ItemCategoryID=ic.ItemCategoryID     
----------------------------------    
,                       
  vwSpecialInvoiceDiffGodown vw, acustomermaster c, acountrymaster cm                        
where                       
 vw.idshopid = invd.idshopid and vw.idinvoiceid = invd.idinvoiceid and                       
 vw.iditemid = invd.iditemid and ih.ihshopid = invd.idshopid and ih.ihinvoiceid =                       
 invd.idinvoiceid and ihcancelled=0 and ihcashinvoice =0 and idratetype = 0 and                       
 ihproforma = 0 and ihcustomerid = c.customerid and  c.countryid = cm.countryid                      
 and ihTransfinished = 1 --and vw.idInvoiceId=724 and vw.idShopId=6                      
group by                       
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihCustomerID, ihbankcashaccid,                      
 ihexchangerate, ihcustomerid, ihdepartmentid, countryname, ihinvoiceno,                       
 customercardno, Customername, ihReferenceNo, ihDepExRate,ihNoofOCDetails,    
 ic.ItemCategoryID,CategoryNameDescription ----RefNo: 02               
                      
union all                      
-- 7. shop credit service invoice                      
select                       
 vws.sicompanyid, vws.sishopid, vws.siinvoicedate, lah.aibankcashid,                       
 convert(numeric(18,2),vws.siamount ) as amount, lah.aicashinvoice,                       
 's' as transtype, lah.aiCustomerid, lah.aidepartmentid,                       
 0.0 cAmt, 0.0 DepAmount, 0.0 CmpAmount, countryname, lah.aiinvoiceno,                       
 convert(numeric(18, 2), vws.siamount) profit,                       
 convert(numeric(18, 2), vws.siamount * aiDepExRate) DepProfit,                       
 convert(numeric(18, 2), vws.siamount * aiExchangeRate) CmpProfit,                       
 customercardno, convert(numeric(18,2), vws.siamount * lah.aiDepExRate ) depsalesamt,                       
 convert(numeric(18,2), vws.siamount * lah.aiExchangeRate) cmpSalesAmt, CustomerName, aiReferenceno,    
null,null ----RefNo: 02                      
from                       
 vwshopservicesales vws , LOsAccountsInvoiceHeader lah, acustomermaster c,                       
 acountrymaster cm                       
where                  
 aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                       
 aishopid = sishopid and lah.aicashinvoice=0 and aicustomerid = c.customerid and                        
 c.countryid = cm.countryid                      
                      
union all                       
                      
-- 8. hq cash service invoice                      
select                       
 ah.companyid, null, ah.invoicedate, ah.bankcashid,                       
 convert(numeric(18,2),sum(serviceqty * amount) ) as amount ,                       
 0 , 'as' as transtype, ah.Customerid,ah.departmentid,                       
 0.0 cAmt, 0.0 DepAmount, 0.0 CmpAmount, countryname, invoiceno,                      
 convert(numeric(18, 2), sum(serviceqty * amount)) profit,                       
 convert(numeric(18, 2), sum(serviceqty * amount) * ah.DepExRate) DepProfit,                       
 convert(numeric(18, 2), sum(serviceqty * amount) * ah.ExchangeRate) CmpProfit,                       
 CustomerCardNo, convert(numeric(18,2),sum(serviceqty * amount) * ah.depExRate)  depsalesamt,                       
 convert(numeric(18,2),sum(serviceqty * amount) * ah.ExchangeRate)  cmpsalesamt,                       
 CustomerName, ReferenceNo ,    
null,null ----RefNo: 02                     
from                       
 ServiceInvoiceDetails sd, AccountsInvoiceHeader ah, acustomermaster c,                       
 acountrymaster cm                      
where          
 ah.invoiceid=sd.invoiceid and ah.companyid = sd.companyid and ah.cancelled=0 and                      
 ah.proforma=0  and ah.cashinvoice = 0 and ah.customerid = c.customerid and                       
 C.Countryid = cm.countryid                       
group by                       
 ah.companyid, ah.invoicedate, ah.bankcashid, ah.exchangerate, ah.customerid,                      
 Ah.departmentid, countryname, invoiceno, customercardno,Customername, ReferenceNo,                       
 ah.DepExRate                      
union all                      
                      
-- 9. shop cash sales                      
select                       
 poshcompanyid, poshshopid, poshbilldate, poshcashaccid,                       
 convert(numeric(18,2), sum(posdunitprice)) as amount,                       
 1 as cashsales, 'c' as transtype, poshCustomerId, poshdepartmentid,                       
 convert(numeric(18, 2), sum(posdcostprice * invd.posdquantity)) camt,                      
 convert(numeric(18, 2), sum(posdcostprice * invd.posdquantity) * ih.poshDepExRate) DepAmount,                      
 convert(numeric(18, 2), sum(posdcostprice * invd.posdquantity) * ih.poshExchangeRate) CmpAmount,                      
 countryname, poshbillno, sum(posdunitprice ) - sum(posdcostprice*invd.posdquantity) profit,                       
 (sum(posdunitprice) * ih.poshDepExRate) - (sum(posdcostprice * invd.posdquantity) * poshDepExRate) DepProfit,                       
 (sum(posdunitprice) * ih.poshExchangeRate) - (sum(posdcostprice * invd.posdquantity) * ih.poshExchangeRate) CmpProfit,                       
 customercardno , convert(numeric(18,2), sum(posdunitprice) * poshdepexRate) as depsalesamt,                      
 convert(numeric(18,2), sum(posdunitprice)*poshExchangeRate) as cmpsalesamt,                   
 case isnull(poshcustomerid ,'')when '' then ih.poshCustomerName else CustomerName end as Customername, '',    
ic.ItemCategoryID,CategoryNameDescription ----RefNo: 02                      
from                       
 losposheader ih                       
 left outer join acustomermaster c on poshcustomerid = c.customerid                       
 left outer join acountrymaster cm on c.CountryId = cm.CountryId,                       
 losposdetail invd      
---------------------------------RefNo: 02    
 left outer join aitem i on  invd.posdItemID=i.ItemID      
 left outer join aitemcategory ic on i.ItemCategoryID=ic.ItemCategoryID      
-------------------------------                     
where               
 ih.poshshopid = invd.posdshopid and ih.poshbillid = invd.posdbillid and                       
 poshcancelled = 0                       
group by                       
 poshcompanyid, poshshopid, poshbilldate, poshbillid, poshcashaccid,                       
 poshexchangerate, poshCustomerId, poshdepartmentid, countryname, poshbillno,                       
 customercardno, Customername, poshdepexRate  ,ih.poshCustomerName,    
ic.ItemCategoryID,CategoryNameDescription ----RefNo: 02                    
                      
union all                      
--jyothish changed -ve to depsales and cmpsalses                      
--10. shop Exchange out                      
select                       
 sehcompanyid, sehshopid, sehexchangedate, sehCashAccID,                       
 convert(numeric(18,2),sum(sedunitprice)) as amount,                       
 1 as cashsales, 'c' as transtype, poshCustomerId, sehdepartmentid,                       
 convert(numeric(18, 2), sum(sedcostprice * invd.sedquantity)) camt,                      
 convert(numeric(18, 2), sum(sedcostprice * invd.sedquantity) * sehDepExRate) DepAmount,                      
 convert(numeric(18, 2), sum(sedcostprice * invd.sedquantity) * sehExchangeRate) CmpAmount,                      
 countryname, sehExchangeNo,                       
 sum(sedunitprice) - sum(sedcostprice * invd.sedquantity) profit,                       
 (sum(sedunitprice) - sum(sedcostprice * invd.sedquantity)) * sehDepExRate DepProfit,                       
 (sum(sedunitprice) - sum(sedcostprice * invd.sedquantity)) * sehExchangeRate CmpProfit,                       
 customercardno, convert(numeric(18,2),sum(sedunitprice) * sehdepExRate)  depsalesamt,                      
 convert(numeric(18,2),sum(sedunitprice) * sehExchangeRate)  cmpsalesamt,                  
 case isnull(poshcustomerid,'')when '' then Sehexchangername else CustomerName end as CustomerName, '',    
ic.ItemCategoryID,CategoryNameDescription --RefNo: 02                      
from                       
 losposexchangeheader ih, losposexchangedetail invd    
------------------------------------RefNo: 02    
 left outer join aitem i on  invd.sedItemID=i.ItemID      
 left outer join aitemcategory ic on i.ItemCategoryID=ic.ItemCategoryID     
----------------------------------    
,                       
 losposheader left outer join acustomermaster c                       
 on poshcustomerid = c.customerid                       
 left outer join acountrymaster cm on c.CountryId = cm.CountryId                       
where                       
 ih.sehshopid = invd.sedshopid and ih.sehexchangeid  = invd.sedexchangeid and                       
 sehcancelled=0 and sehbillid = poshbillid and sehshopid = poshshopid and                       
 sedbillorexchange = 'E'                      
group by                       
 sehcompanyid, sehshopid, sehexchangedate, sehexchangeid, sehcashaccid,                       
 poshexchangerate, poshCustomerId, sehdepartmentid, countryname, sehExchangeNo,                       
 customercardno, sehexchangerate, Customername, sehDepExRate,Sehexchangername                      
 ,ic.ItemCategoryID,CategoryNameDescription  ----RefNo: 02                     
Union All                      
                      
-- 11. shop Exchange in           
-----jyothish changed -ve to depsales and cmpsalses                       
select                       
 sehcompanyid, sehshopid, sehexchangedate, sehCashAccID,                       
 convert(numeric(18,2), -sum(sedunitprice)) as amount,                       
 1 as cashsales, 'c' as transtype, poshCustomerId, sehdepartmentid,                       
 convert(numeric(18, 2), -sum(sedcostprice * invd.sedExchangeQty)) camt,                      
 convert(numeric(18, 2), -sum(sedcostprice * invd.sedExchangeqty) * sehDepExRate) DepAmount,                      
 convert(numeric(18, 2), -sum(sedcostprice * invd.sedExchangeqty) * sehExchangeRate) CmpAmount,                      
 countryname, sehExchangeNo, -sum(sedunitprice) - sum(sedcostprice * invd.sedExchangeqty) profit,                       
 -(sum(sedunitprice) - sum(sedcostprice * invd.sedExchangeqty)) * sehDepExRate DepProfit,                       
 -(sum(sedunitprice) - sum(sedcostprice * invd.sedExchangeqty)) * sehExchangeRate CmpProfit,                       
 customercardno ,- convert(numeric(18,2),sum(sedunitprice) * sehdepExRate)  depsalesamt,                      
 -convert(numeric(18,2),sum(sedunitprice) * sehExchangeRate)  cmpsalesamt,                    
case isnull(poshcustomerid,'')when '' then Sehexchangername else CustomerName end as CustomerName, '',    
ic.ItemCategoryID,CategoryNameDescription ----RefNo: 02                  
from                       
 losposexchangeheader ih, losposexchangedetail invd    
-------------------------------------------RefNo: 02    
left outer join aitem i on  invd.sedItemID=i.ItemID      
 left outer join aitemcategory ic on i.ItemCategoryID=ic.ItemCategoryID     
-----------------------------------------    
,                       
 losposheader left outer join acustomermaster c                       
 on poshcustomerid = c.customerid                       
 left outer join acountrymaster cm                       
 on c.CountryId = cm.CountryId                      
where                       
 ih.sehshopid = invd.sedshopid and ih.sehexchangeid  = invd.sedexchangeid                       
 and sehcancelled = 0 and sehbillid = poshbillid and sehshopid = poshshopid and                       
 sedbillorexchange = 'B' and sedExchangeQty > 0                       
group by                       
 sehcompanyid, sehshopid, sehexchangedate, sehexchangeid,                
 sehcashaccid, poshexchangerate, poshCustomerId,sehdepartmentid, countryname,                       
 sehExchangeNo, customercardno, sehexchangerate, Customername, sehdepExRate,Sehexchangername                      
  ,ic.ItemCategoryID,CategoryNameDescription ----RefNo: 02                    
union all                      
                      
---- 12. shop credit rexport invoices - 22/12/2002                      
select                       
 rehcompanyid, rehshopid, rehexportdate, rehbankcashaccid,                       
 convert(numeric(18,2), sum(isnull(redunitprice,0)) ) as amount, 0 rehCashInvoice,                       
 'c' as transtype , ih.rehCustomerid, ih.rehdepartmentid,                      
 convert(numeric(18, 2), sum(isnull(redcostprice,0) * invd.redquantity)) cAmt,                       
 convert(numeric(18, 2), sum(isnull(redcostprice,0) * invd.redquantity) * rehDepExRate) DepAmount,                       
 convert(numeric(18, 2), sum(isnull(redcostprice,0) * invd.redquantity) * rehExchangeRate) CmdAmount,                       
 countryname, rehExportNo,                      
 convert(numeric(18, 2), sum(redunitprice) - sum(redcostprice * invd.redquantity)) profit,                       
 convert(numeric(18, 2), sum(redunitprice) * rehDepExRate - sum(redcostprice * invd.redquantity) * rehDepExRate) DepProfit,                      
 convert(numeric(18, 2), sum(redunitprice) * rehExchangeRate - sum(redcostprice * invd.redquantity) * rehExchangeRate) CmpProfit,                      
 CustomerCardNo, convert(numeric(18,2),sum(redunitprice ) * rehDepExRate) as depsalesamt,                       
 convert(numeric(18,2),sum(redunitprice) * rehExchangerate  ) as cmpSalesamt, CustomerName, rehReferenceno ,    
ic.ItemCategoryID,CategoryNameDescription ----RefNo: 02                     
from                       
 losExportHeader ih, losExportDetail invd, acustomermaster c, acountrymaster cm,    
aitem i,aitemcategory ic  ----RefNo: 02                       
where                       
 ih.rehshopid = invd.redshopid and ih.rehExportID = invd.redExportID and             
 rehcancelled=0 and rehcashinvoice =0 and rehproforma = 0 and                       
 rehcustomerid = c.customerid and c.countryid = cm.countryid and                       
 rehcustomerid is not null and rehtype='i'      
and i.ItemID=invd.redItemID and i.ItemCategoryID=ic.ItemCategoryID ----RefNo: 02                    
group by                       
 rehcompanyid, rehshopid, rehExportNo, rehExportDate, rehExportID, rehCustomerID,                       
 rehbankcashaccid, rehexchangerate, rehCustomerid ,rehdepartmentid,                      
 countryname, rehExportNO, CustomerCardNo, Customername, rehReferenceno, rehDepExRate,    
ic.ItemCategoryID,CategoryNameDescription ----RefNo: 02                      
                      
union all                       
                      
                      
                      
--13 Goods return note  - Kishore 23/06/2003                      
select grnCompanyId, grnhShopId, grnhGoodsReturnNoteDate, grnReturnAccId,                       
-convert(numeric(18,2), sum(grndUnitPrice * grnhExchangeRate)) as amount,                       
0 as CashSales, 'gr' as TransType, GrnhCustomerID, grnhdepartmentid,                       
-convert(numeric(18,2), sum(grnCostPrice * invd.grndQuantity)) camt,                      
-convert(numeric(18,2), sum(grnCostPrice * invd.grndQuantity) * grnhdepExRate) depamt,                      
-convert(numeric(18,2), sum(grnCostPrice * invd.grndQuantity) * grnhExchangeRate) cmdamt,                      
isnull(countryname, '') countryname , GrnhGoodsreturnnoteNO,                       
-(sum(grndUnitPrice) * grnhExchangeRate -                       
sum(grnCostPrice * invd.grndQuantity)) profit,            
--RefNo:01                  
-convert(numeric(18, 2), sum(grndUnitPrice) * grnhdepExRate -                      
sum(grnCostPrice * invd.grndQuantity * grnhdepExRate)) DepProfit,         
 --RefNo:01                      
-convert(numeric(18, 2), sum(grndUnitPrice) * grnhExchangeRate -                     
sum(grnCostPrice * invd.grndQuantity * grnhExchangeRate)) CmpProfit,                      
isnull(CustomerCardNo ,'') CustomerCardNo,                      
-sum(grndunitprice) * grnhDepExRate  as depsalesamt,                       
convert(numeric(18,2),-sum(grndunitprice) * grnhExchangerate) as cmpSalesamt,                      
c.CustomerName, '',    
ic.ItemCategoryID,CategoryNameDescription ----RefNo: 02                      
from losGoodsReturnNoteHeader ih left outer join acustomermaster c                       
on GrnhCustomerID = c.customerid left outer join acountrymaster cm                      
on c.CountryId = cm.CountryId,                       
losGoodsReturnNoteDetail invd, aItem i, aItemCategory ic                         
where ih.grnhshopid = invd.grndshopid                       
and ih.grnhGoodsReturnNoteId  = invd.GRNDReturnNoteID                       
and GrnhCancel = 0                       
and invd.grndQuantity > 0                       
and invd.grndItemId = i.ItemId                      
and i.ItemCategoryId = ic.ItemCategoryId                      
group by grncompanyid, grnhshopid, i.Brand, ic.CategoryNameDescription,                       
GrnhGoodsreturnnoteDate, c.customername ,                      
grnhGoodsReturnNoteId, ih.GrnhGoodsreturnnoteNO, grnReturnAccId, grnhExchangeRate,                       
GrnhCustomerID, grnhdepartmentid, countryname, customercardno, grnhexchangerate,                       
grnhDepExRate,    
ic.ItemCategoryID,CategoryNameDescription----RefNo: 02                      
                
union all                
-- 14. shop credit special invoice for Return After Despatch                     
select                       
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcashaccid,                       
 convert(numeric(18,2),sum(vw.idunitprice ) ) amount,                       
 0 ihcashinvoice, 'RAD' as transtype, ihCustomerId, ihdepartmentid,                       
 convert(numeric(18, 2), sum(vw.costprice * Abs(invd.reqqty))) camt,                       
 convert(numeric(18, 2), sum(vw.costprice * Abs(invd.reqqty)) * ihDepExRate) DepAmount,                      
 convert(numeric(18, 2), sum(vw.costprice * Abs(invd.reqqty)) * ihExchangeRate) CmpAmount,                      
 countryname, ihinvoiceno,                      
 -convert(numeric(18, 2), Abs(sum(vw.idunitprice)) - Abs(sum(idcostprice * Abs(invd.reqqty)))) profit,                       
 -convert(numeric(18, 2), (Abs(sum(vw.idunitprice)) * ihDepExRate) - sum(idcostprice * Abs(invd.reqqty)) * ihDepExRate) DepProfit,                      
 -convert(numeric(18, 2), (Abs(sum(vw.idunitprice)) * ihExchangeRate) - sum(idcostprice * Abs(invd.reqqty)) * ihExchangeRate) CmpProfit,                      
 customercardno , convert(numeric(18,2),sum(vw.idunitprice)* ihDepExRate) as depsalesamt,                       
 convert(numeric(18,2),sum(vw.idunitprice* ihExchangerate) ) as cmpSalesamt, CustomerName, ihReferenceNo,    
ic.ItemCategoryID,CategoryNameDescription ----RefNo: 02                      
from                       
  losspecialinvoiceheader ih, (select idinvoiceID,idShopId,iditemid,idRateType,sum(reqqty)reqqty,idCostPrice               
  from losspecialinvoicedetail group by idinvoiceID,idShopId,iditemid,idRateType,idCostPrice) invd    
-------------------------------------------RefNo: 02    
left outer join aitem i on  invd.iditemid=i.ItemID      
 left outer join aitemcategory ic on i.ItemCategoryID=ic.ItemCategoryID     
-----------------------------------------     
,                       
  vwSpecialInvoiceDiffGodown vw, acustomermaster c, acountrymaster cm                        
where                       
 vw.idshopid = invd.idshopid and vw.idinvoiceid = invd.idinvoiceid and                       
 vw.iditemid = invd.iditemid and ih.ihshopid = invd.idshopid and ih.ihinvoiceid =                       
 invd.idinvoiceid and ihcancelled=0 and ihcashinvoice =0 and idratetype = 1 and                       
 ihproforma = 0 and ihcustomerid = c.customerid and  c.countryid = cm.countryid                      
 and ihTransfinished = 1 --and vw.idInvoiceId=762 and vw.idShopId=6                     
group by                       
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihCustomerID, ihbankcashaccid,                      
 ihexchangerate, ihcustomerid, ihdepartmentid, countryname, ihinvoiceno,                       
 customercardno, Customername, ihReferenceNo, ihDepExRate,    
 ic.ItemCategoryID,CategoryNameDescription    --RefNo: 02 

--RefNo-04 start
union all

/*
select serinvhrefno,serinvhcustname,serinvno,serinvhCashInv,serinvhcashacc,serinvhsalesacc,serinvhservacc from
losserviceinvheader
*/
 --Service Invoice (cash-1)
  select                   
   serinvhcompanyid,serinvhshopid,serinvhdate,serinvhservacc, 
   convert(numeric(18,2),sum(repinvdrate * repinvdqty)) amount,
   1 as cashsales, 'c' as transtype,serinvhCustomerId,serinvhdepartmentid, 
   convert(numeric(18,2),sum(repinvdcostprice * repinvdqty)) camt,
   convert(numeric(18,2),sum(repinvdcostprice * seinvhdepexrate * repinvdqty))DepAmount,                  
   convert(numeric(18,2), sum(repinvdcostprice * serinvhcmpexrate * repinvdqty)) CmpAmount,                  
   countryname,serinvno,
   convert(numeric(18,2),(sum(repinvdrate*repinvdqty)) - (sum(repinvdcostprice*repinvdqty))) profit,
   convert(numeric(18,2),(sum(repinvdrate*repinvdqty)* seinvhdepexrate) - (sum(repinvdcostprice*repinvdqty)* seinvhdepexrate)) DepProfit,
   convert(numeric(18,2),(sum(repinvdrate*repinvdqty)* serinvhcmpexrate) - (sum(repinvdcostprice*repinvdqty)* serinvhcmpexrate)) CmpProfit,
   CustomerCardNo , 
   convert(numeric(18,2), sum(repinvdrate*repinvdqty)* seinvhdepexrate) as depsalesamt,                      
   convert(numeric(18,2), sum(repinvdrate*repinvdqty)* serinvhcmpexrate) as cmpsalesamt,
   serinvhcustname as Customername, '',    
   ic.ItemCategoryID,CategoryNameDescription 
  from losserviceinvheader
	  left outer join acustomermaster c on losserviceinvheader.serinvhCustomerId = c.customerid                       
	  left outer join acountrymaster cm on c.CountryId = cm.CountryId,
	  losinvoicedpartsreplacedetails     
	  left outer join aitem i on  losinvoicedpartsreplacedetails.repinvdpartsid=i.ItemID      
	  left outer join aitemcategory ic on i.ItemCategoryID=ic.ItemCategoryID      
	  ,ashops s, adepartmentmaster d
  where                   
	serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
	and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1                  
	and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0                
  group by     
  serinvhcompanyid,serinvhshopid,serinvhdate,serinvhid,serinvhservacc,
  serinvhcmpexrate,seinvhdepexrate,serinvhCustomerId,serinvhcustname,serinvhdepartmentid,
  countryname,serinvno,customercardno, ic.ItemCategoryID,CategoryNameDescription

union all

--Service Invoice (cash-2)
 select                   
   serinvhcompanyid,serinvhshopid,serinvhdate,serinvhservacc, 
   convert(numeric(18,2),(serinvhserviceamt)) amount,
   1 as cashsales, 'c' as transtype,serinvhCustomerId,serinvhdepartmentid, 
   --convert(numeric(18,2),sum(repinvdcostprice * repinvdqty)) camt,
   --convert(numeric(18,2),sum(repinvdcostprice * seinvhdepexrate * repinvdqty))DepAmount,                  
   --convert(numeric(18,2), sum(repinvdcostprice * serinvhcmpexrate * repinvdqty)) CmpAmount,                  
   0 camt,0 DepAmount,0 CmpAmount,
   countryname,serinvno,
   --convert(numeric(18,2),(sum(repinvdrate*repinvdqty)) - (sum(repinvdcostprice*repinvdqty))) profit,
   --convert(numeric(18,2),(sum(repinvdrate*repinvdqty)* seinvhdepexrate) - (sum(repinvdcostprice*repinvdqty)* seinvhdepexrate)) DepProfit,
   --convert(numeric(18,2),(sum(repinvdrate*repinvdqty)* serinvhcmpexrate) - (sum(repinvdcostprice*repinvdqty)* serinvhcmpexrate)) CmpProfit,
   0 profit,0 DepProfit,0 CmpProfit,
   CustomerCardNo , 
   convert(numeric(18,2), (serinvhserviceamt)* seinvhdepexrate) as depsalesamt,                      
   convert(numeric(18,2), (serinvhserviceamt)* serinvhcmpexrate) as cmpsalesamt,
   serinvhcustname as Customername, '',    
   ic.ItemCategoryID,CategoryNameDescription 
  from losserviceinvheader
	  inner join losinvoicedpartsreplacedetails   on repinvinvoiceid =serinvhid 
			and repinvdshopid=serinvhshopid
	  left outer join acustomermaster c on losserviceinvheader.serinvhCustomerId = c.customerid                       
	  left outer join acountrymaster cm on c.CountryId = cm.CountryId
	  left outer join aitem i on  losinvoicedpartsreplacedetails.repinvdpartsid=i.ItemID      
	  left outer join aitemcategory ic on i.ItemCategoryID=ic.ItemCategoryID      
	  ,ashops s, adepartmentmaster d
  where    
     serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1                  
    and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
--group by
--  serinvhcompanyid,serinvhshopid,serinvhdate,serinvhid,serinvhservacc,
--  serinvhcmpexrate,seinvhdepexrate,serinvhCustomerId,serinvhcustname,serinvhdepartmentid,
--  countryname,serinvno,customercardno, ic.ItemCategoryID,CategoryNameDescription

union all

 --Service Invoice (credit-1)
  select                   
   serinvhcompanyid,serinvhshopid,serinvhdate,serinvhservacc, 
   convert(numeric(18,2),sum(repinvdrate * repinvdqty)) amount,
   0 as cashsales, 'c' as transtype,serinvhCustomerId,serinvhdepartmentid, 
   convert(numeric(18,2),sum(repinvdcostprice * repinvdqty)) camt,
   convert(numeric(18,2),sum(repinvdcostprice * seinvhdepexrate * repinvdqty))DepAmount,                  
   convert(numeric(18,2), sum(repinvdcostprice * serinvhcmpexrate * repinvdqty)) CmpAmount,                  
   countryname,serinvno,
   convert(numeric(18,2),(sum(repinvdrate*repinvdqty)) - (sum(repinvdcostprice*repinvdqty))) profit,
   convert(numeric(18,2),(sum(repinvdrate*repinvdqty)* seinvhdepexrate) - (sum(repinvdcostprice*repinvdqty)* seinvhdepexrate)) DepProfit,
   convert(numeric(18,2),(sum(repinvdrate*repinvdqty)* serinvhcmpexrate) - (sum(repinvdcostprice*repinvdqty)* serinvhcmpexrate)) CmpProfit,
   CustomerCardNo , 
   convert(numeric(18,2), sum(repinvdrate*repinvdqty)* seinvhdepexrate) as depsalesamt,                      
   convert(numeric(18,2), sum(repinvdrate*repinvdqty)* serinvhcmpexrate) as cmpsalesamt,
   serinvhcustname as Customername, '',    
   ic.ItemCategoryID,CategoryNameDescription 
  from losserviceinvheader
	  left outer join acustomermaster c on losserviceinvheader.serinvhCustomerId = c.customerid                       
	  left outer join acountrymaster cm on c.CountryId = cm.CountryId,
	  losinvoicedpartsreplacedetails     
	  left outer join aitem i on  losinvoicedpartsreplacedetails.repinvdpartsid=i.ItemID      
	  left outer join aitemcategory ic on i.ItemCategoryID=ic.ItemCategoryID      
	  ,ashops s, adepartmentmaster d
  where                   
	serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
	and repinvdshopid = shopid and serinvhcashacc is null                   
	and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid                    
	and Patindex('%y%',repinvdtype)>0                
  group by     
  serinvhcompanyid,serinvhshopid,serinvhdate,serinvhid,serinvhservacc,
  serinvhcmpexrate,seinvhdepexrate,serinvhCustomerId,serinvhcustname,serinvhdepartmentid,
  countryname,serinvno,customercardno, ic.ItemCategoryID,CategoryNameDescription

union all
 --Service Invoice (credit-2)
 select                   
   serinvhcompanyid,serinvhshopid,serinvhdate,serinvhservacc, 
   convert(numeric(18,2),(serinvhserviceamt)) amount,
   0 as cashsales, 'c' as transtype,serinvhCustomerId,serinvhdepartmentid, 
   --convert(numeric(18,2),sum(repinvdcostprice * repinvdqty)) camt,
   --convert(numeric(18,2),sum(repinvdcostprice * seinvhdepexrate * repinvdqty))DepAmount,                  
   --convert(numeric(18,2), sum(repinvdcostprice * serinvhcmpexrate * repinvdqty)) CmpAmount,                  
   0 camt,0 DepAmount,0 CmpAmount,
   countryname,serinvno,
   --convert(numeric(18,2),(sum(repinvdrate*repinvdqty)) - (sum(repinvdcostprice*repinvdqty))) profit,
   --convert(numeric(18,2),(sum(repinvdrate*repinvdqty)* seinvhdepexrate) - (sum(repinvdcostprice*repinvdqty)* seinvhdepexrate)) DepProfit,
   --convert(numeric(18,2),(sum(repinvdrate*repinvdqty)* serinvhcmpexrate) - (sum(repinvdcostprice*repinvdqty)* serinvhcmpexrate)) CmpProfit,
   0 profit,0 DepProfit,0 CmpProfit,
   CustomerCardNo , 
   convert(numeric(18,2), (serinvhserviceamt)* seinvhdepexrate) as depsalesamt,                      
   convert(numeric(18,2), (serinvhserviceamt)* serinvhcmpexrate) as cmpsalesamt,
   serinvhcustname as Customername, '',    
   ic.ItemCategoryID,CategoryNameDescription 
  from losserviceinvheader
  	  inner join losinvoicedpartsreplacedetails   on repinvinvoiceid =serinvhid 
			and repinvdshopid=serinvhshopid
	  left outer join acustomermaster c on losserviceinvheader.serinvhCustomerId = c.customerid                       
	  left outer join acountrymaster cm on c.CountryId = cm.CountryId
	  left outer join aitem i on  losinvoicedpartsreplacedetails.repinvdpartsid=i.ItemID      
	  left outer join aitemcategory ic on i.ItemCategoryID=ic.ItemCategoryID      
	  ,ashops s, adepartmentmaster d
  where                       
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                   
--group by
--  serinvhcompanyid,serinvhshopid,serinvhdate,serinvhid,serinvhservacc,
--  serinvhcmpexrate,seinvhdepexrate,serinvhCustomerId,serinvhcustname,serinvhdepartmentid,
--  countryname,serinvno,customercardno, ic.ItemCategoryID,CategoryNameDescription

--RefNo-04 ends

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

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionWithMarginDetWithOutGST')
   DROP view dbo.vwDailySalesCollectionWithMarginDetWithOutGST
GO


---Created ON :13/01/2008
---Comments   :For Daily Sales With Returns Report   
---------------------------------------------------------------------------------------                
--RefNo        : RefNo-2
--Modified by  : Bijesh.B
--Date         : 21/06/2011
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-3
--Modified by  : Bijesh.B
--Date         : 29/07/2011
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong
--             : since, Special invoice return after desp, reqqty is negative,
--				 -1 is multiplied with reqqty
----------------------------------------------------------------------------------------------   
--RefNo        : Newly created view (copy of vwDailySalesCollectionWithMarginDet)
--Modified by  : Bijesh.B
--Date         : 13/03/2012
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Need to show GST separately
----------------------------------------------------------------------------------------------   
--RefNo-4
--Modified by  : Bijesh.B
--Date         : 13/07/2012
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Need to show GST separately - corrected values
----------------------------------------------------------------------------------------------   
--Modified by  : BIJESH.B   
--RefNo        : RefNo-5
--Date         : 01/08/2012  
--Comments     : Corrected Other Charges Service Tax in Credit Invoice
----------------------------------------------------------------------------------------------       

create VIEW [dbo].[vwDailySalesCollectionWithMarginDetWithOutGST] AS          
Select           
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,           
 cashcreditcollection.poshbilldate, 
 convert(numeric(18,8),sum(cashsales)) cashsales,          
 convert(numeric(18,8),sum(dcashsales)) dcashsales,           
 convert(numeric(18,8),sum(ccashsales)) ccashsales,          
 convert(numeric(18,8),sum(creditsales)) creditsales,          
 convert(numeric(18,8),sum(dcreditsales)) dcreditsales,           
 convert(numeric(18,8),sum(ccreditsales)) ccreditsales,           
 convert(numeric(18,8),sum(costvalue)) costvalue,          
 convert(numeric(18,8),sum(dcostvalue)) dcostvalue,           
 convert(numeric(18,8),sum(ccostvalue)) ccostvalue,           
 convert(numeric(18,8),sum(margin)) margin,          
 convert(numeric(18,8),sum(dmargin)) dmargin,           
 convert(numeric(18,8),sum(cmargin)) cmargin,
 convert(numeric(18,8),sum(Exchange)) Exchange,          
 convert(numeric(18,8),sum(dExchange)) dExchange,           
 convert(numeric(18,8),sum(cExchange)) cExchange,
 convert(numeric(18,8),sum(GReturn)) GReturn,          
 convert(numeric(18,8),sum(dGReturn)) dGReturn,           
 convert(numeric(18,8),sum(cGReturn)) cGReturn,           
 cashcreditcollection.departmentname, cashcreditcollection.departmentid           
--RefNo-2 start -------------------------
,convert(numeric(18,8),sum(PdChequeSales)) PdChequeSales,
convert(numeric(18,8),sum(dPdChequeSales)) dPdChequeSales,
convert(numeric(18,8),sum(cPdChequeSales)) cPdChequeSales,
--RefNo-2 ends -------------------------
convert(numeric(18,8),sum(GSTAmount))GSTAmount,
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount

from           
 (          
  select           
   shopname, losposheader.poshShopID, poshbilldate, 
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales, 
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dcashsales,
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) ccashsales,
   0.0 creditsales, 0.0 dcreditsales,0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,           
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,           
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,          
   (convert(numeric(18,8), sum(posdunitprice -isnull(posdItemTaxAmount,0)))) - 
		sum(posdcostprice*posdquantity) margin, 
   (convert(numeric(18,8), sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshdepexrate))) -           
		sum(posdcostprice*posdquantity) * poshdepexrate dmargin, 
   (convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshexchangerate))) - 
		sum(posdcostprice*posdquantity) * poshexchangerate cmargin,           
   0.00 Exchange,0.00 dExchange,0.00 cExchange,0.00 GReturn,0.00 dGReturn,0.00 cGReturn,
   departmentname, poshdepartmentid  departmentid          
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount
  from           
   losposdetail, losposheader, ashops s, adepartmentmaster d           
  where           
   poshBillid=posdBillid and poshShopid=posdshopid AND           
   s.shopid = posdshopid and POSHCANCELLED=0 and           
   poshDepartmentid = d.departmentid          
   and isnull(PosPostDate,0)=0 --RefNo-2  if No PD Cheque Amt involved                       
  group by           
   shopname, departmentname, poshdepartmentid, poshshopid, poshbilldate, 
   poshdepexrate, poshexchangerate,poshBillid          
     
--RefNo-2 Start --------------------------------------------
 --CASH + PD CHEQUE -> Taking only cash amount
union all
select           
   shopname, losposheader.poshShopID, poshbilldate, 
   --convert(numeric(18,8),sum(posdunitprice )) cashsales, 
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)) dcashsales, 
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)) ccashsales,

   --convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))-pdCheque.PosBankAmount) cashsales, 
   --convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshdepexrate)-pdCheque.PosBankAmount) dcashsales, 
   --convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshexchangerate)-pdCheque.PosBankAmount) ccashsales,
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,
   0.0 creditsales, 0.0 dcreditsales,           
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,           
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,           
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,          
   (convert(numeric(18,8), sum(posdunitprice -isnull(posdItemTaxAmount,0) ))) -           
		sum(posdcostprice*posdquantity) margin, 
   (convert(numeric(18,8), sum(posdunitprice -isnull(posdItemTaxAmount,0) * poshdepexrate))) -           
		sum(posdcostprice*posdquantity) * poshdepexrate dmargin, 
   (convert(numeric(18,8),sum(posdunitprice -isnull(posdItemTaxAmount,0) * poshexchangerate))) - 
		sum(posdcostprice*posdquantity) * poshexchangerate cmargin,           
   0.00 Exchange,0.00 dExchange,0.00 cExchange,0.00 GReturn,0.00 dGReturn,0.00 cGReturn,departmentname, poshdepartmentid  departmentid          
   --,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales, 
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dPdChequeSales,
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) cPdChequeSales
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount

  from           
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque           
  where           
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND           
   s.shopid = posdshopid and POSHCANCELLED=0 and           
   poshDepartmentid = d.departmentid 
   and isnull(PosPostDate,0)=1 --if PD Cheque Amt is involved  
   and pdCheque.PoshBillID =losposheader.poshbillid
   and pdCheque.PoshShopID =losposheader.poshShopID            
  group by           
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,          
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount          

/*
union all
 --CASH + PD CHEQUE -> Taking only Cheque amount
 select           
   shopname, losposheader.poshShopID, poshbilldate, 
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,
   0.0 creditsales, 0.0 dcreditsales,           
   0.0 ccreditsales,
   /*
   sum(posdcostprice * posdquantity) costvalue,           
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,           
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,          
   (convert(numeric(18,8), sum(posdunitprice ))) -           
   sum(posdcostprice*posdquantity) margin, (convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -           
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin, (convert(numeric(18,8),           
   sum(posdunitprice * poshexchangerate))) - sum(posdcostprice*posdquantity) * poshexchangerate cmargin,
   */
   0.0 costvalue,0.0 dcostvalue,0.0 ccostvalue, 
   0.0 margin,0.0 dmargin,0.0 cmargin,             
   0.00 Exchange,0.00 dExchange,0.00 cExchange,0.00 GReturn,0.00 dGReturn,
   0.00 cGReturn,departmentname, poshdepartmentid  departmentid,          
   pdCheque.PosBankAmount as PdChequeSales,
   (pdCheque.PosBankAmount * poshdepexrate) as  dPdChequeSales,
   (pdCheque.PosBankAmount * poshexchangerate) as cPdChequeSales
   ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount
  from           
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque           
  where           
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND   
   s.shopid = posdshopid and POSHCANCELLED=0 and           
   poshDepartmentid = d.departmentid 
   and isnull(PosPostDate,0)=1 --if PD Cheque Amt is involved  
   and pdCheque.PoshBillID =losposheader.poshbillid
   and pdCheque.PoshShopID =losposheader.poshShopID            
  group by           
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,          
   poshdepexrate, poshexchangerate,losposheader.poshBillid ,pdCheque.PosBankAmount 
 --RefNo-2 Ends --------------------------------------------
 */
 union all          

 --RefNo-5 start commented below and added

 -- select           
 --  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
 --  convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,           
 --  convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,           
 --  convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,           
 --  convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,           
 --  convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,          
 --  convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,          
 --  (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -           
	--	sum(isnull(idcostprice*idquantity,0)))) margin,           
 --  (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -           
	--	sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,           
 --  (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) * ihexchangerate -           
	--	sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin
	--,0.00,0.00,0.00,0.00,0.00,0.00,           
 --  departmentname, ihdepartmentid departmentid           
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
 -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,
 --  convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount
 -- from           
 --  losinvoiceheader  ih          
 --  left outer join losinvoicedetail invd          
 --  on ihInvoiceid=idInvoiceid and ihshopid=idshopid           
 --  left outer join           
 --  (select          
 --   ioShopID,ioInvoiceID,sum(ioAmount) ioAmount          
 --  from          
 --   losInvoiceOC           
 --  group by          
 --  ioShopID,ioInvoiceID) ocd           
 --  on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,           
 --  ashops s, adepartmentmaster d           
 -- where           
 --  IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and           
 --  ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'          
 -- group by           
 --  shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,           
 --  ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount          
 
 
   --credit invoice
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) creditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihexchangerate) ccreditsales,             

   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -      
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,  
                    
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) -             
		 sum(isnull(idcostprice*idquantity,0)))) margin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihexchangerate -             
		   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,
		0.00,0.00,0.00,0.00,0.00,0.00,    
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from          
    
     losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid
   
   union all
   
   --Other Charges (Credit Invoice)
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) creditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate) ccreditsales,             
   0 costvalue,0 dcostvalue,0 ccostvalue,                  
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))Margin,            
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))* ihdepexrate  dmargin,             
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))) * ihexchangerate cmargin,  
   0.00,0.00,0.00,0.00,0.00,0.00,  
   departmentname, ihdepartmentid departmentid,
   0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales 
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihexchangerate)cGSTAmount  
  from          
     losinvoiceheader  ih                  
   left outer join losInvoiceOC ocd  on ihshopid= ocd.ioShopid 
			and ihinvoiceid=ocd.ioInvoiceID         
	,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by  
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid,ocd.ioShopID,ocd.ioInvoiceID
--RefNo-5 ends
 
 union all          
          
  select           
   shopname, ihShopID, ihinvoicedate,          
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,           
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,           
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,           
   0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,           
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))) costvalue,           
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,          
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,          
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -           
		sum(isnull(idcostprice*idquantity,0)))) margin,           
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) * ihdepexrate -           
		sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,           
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -           
		sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin
	,0.00,0.00,0.00,0.00,0.00,0.00,           
   departmentname, ihdepartmentid departmentid           
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,
    convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount
  from           
   losinvoiceheader  ih          
   left outer join losinvoicedetail invd          
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid           
   left outer join           
   (select          
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount          
   from          
    losInvoiceOC           
   group by          
   ioShopID,ioInvoiceID) ocd           
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,           
   ashops s, adepartmentmaster d           
  where           
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and           
   ihcashinvoice=1 and ihdepartmentid = d.departmentid and ihtype ='i'          
  group by           
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,           
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount          
          
 union all          
   
   select           
   shopname, sehshopid, sehexchangedate, convert(numeric(18,8),           
   sum(cashsales )) cashsales, convert(numeric(18,8),           
   sum(dcashsales)) dcashsales,convert(numeric(18,8),           
   sum(ccashsales)) ccashsales, 0.0 creditsales,           
   0.0 dcreditsales , 0.0 ccreditsales , sum(costvalue) costvalue,          
   sum(dcostvalue) dcostvalue,sum(ccostvalue) ccostvalue,          
   sum(margin) margin, sum(dmargin) dmargin, sum(cmargin)cmargin,
   0.00,0.00,0.00,0.00,0.00,0.00, departmentname, departmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),sum(GSTAmount)) GSTAmount  
  ,convert(numeric(18,8),sum(dGSTAmount)) dGSTAmount  
  ,convert(numeric(18,8),sum(cGSTAmount)) cGSTAmount  
  from           
      vwPosExchangeDetailsWithMarginWithOutGST      
  group by           
   shopname, sehshopid, departmentname, departmentid, sehexchangedate ,          
   departmentname,sehExchangeID   
  having sum(cashsales )>0       
 
union all  
        
   select           
   shopname, sehshopid, sehexchangedate,0.00,0.00,0.00, 0.0 creditsales,           
   0.0 dcreditsales , 0.0 ccreditsales , sum(costvalue) costvalue,          
   sum(dcostvalue) dcostvalue,sum(ccostvalue) ccostvalue,          
   sum(margin) margin, sum(dmargin) dmargin, sum(cmargin)cmargin,
   convert(numeric(18,8),           
   sum(cashsales )) Exchange, convert(numeric(18,8),           
   sum(dcashsales)) dExchange,convert(numeric(18,8),           
   sum(ccashsales)) cExchange,0.00,0.00,0.00, departmentname, departmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),sum(GSTAmount)) GSTAmount 
  ,convert(numeric(18,8),sum(dGSTAmount)) dGSTAmount  
  ,convert(numeric(18,8),sum(cGSTAmount)) cGSTAmount  

  from           
   vwPosExchangeDetailsWithMarginWithOutGST         
  group by           
   shopname, sehshopid, departmentname, departmentid, sehexchangedate ,          
   departmentname,sehExchangeID   
  having sum(cashsales )<0  

 union all    
 
-- RefNo-3 starts
-- special Invoice (cash)  
select   
shopname,                               
 ihshopid, ihinvoicedate,            
 convert(numeric(18, 8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,
 convert(numeric(18, 8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,
 convert(numeric(18, 8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales, 
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                
 sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
 sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0) )))- sum(idcostprice*reqqty) margin,           
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,      
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0) ))- sum(idcostprice*reqqty))* ihexchangerate cmargin,
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                              
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0 
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                       
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                             
union all                                

-------- special invoice - return before despatch                    
select shopname,                               
  ihshopid, ihinvoicedate,            
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales, 
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                
 -sum(idcostprice * reqqty) costvalue ,
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,           

-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty)) margin,           
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,           
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
 
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1 
 and ihNoofOCDetails<>0    
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                         
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                                    
union all                                

 --Special invoice return  - after desp                              
select shopname,                               
 ihshopid, ihinvoicedate,            
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0))* ihDepExRate) dcashsales,
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales, 
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                
sum(idcostprice * reqqty) costvalue,
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  , 
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) margin,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where  
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1                               
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID  
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
 
-- special Invoice (credit)
union all
select   
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,           
  0.0 ccashsales, 
 convert(numeric(18, 8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) creditsales,
 convert(numeric(18, 8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcreditsales,
 convert(numeric(18, 8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccreditsales, 
 sum(idcostprice * reqqty) costvalue,
 sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
 sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
--(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty) margin,           
--(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
--(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))))-sum(idcostprice*reqqty) margin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
 
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where                                 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                              
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                
 and IhTransFinished = 1 And ihcAshinvoice <>1 and ihNoofOCDetails=0 
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                       
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid,
  ihdepartmentid,     
 ihdepexrate, ihexchangerate
                             
union all                                

-- special invoice - return before despatch                    
select   
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,           
  0.0 ccashsales, 
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0))) creditsales,
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcreditsales,
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccreditsales, 
 
-- sum(idcostprice * reqqty) costvalue,
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,           
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,0.00,0.00,0.00,0.00,0.00,0.00,
 -sum(idcostprice * reqqty) costvalue ,
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,           

-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty)) margin,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice <>1 and ihTransFinished = 1 
 and ihNoofOCDetails<>0    
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                         
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                                    
union all                                
                             
-- Special invoice return  - after desp                              
select   
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,           
  0.0 ccashsales, 
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0))) creditsales,
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcreditsales,
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccreditsales, 
 
 -- sum(idcostprice * reqqty) costvalue,
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,           
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,0.00,0.00,0.00,0.00,0.00,0.00,
sum(idcostprice * reqqty) costvalue,
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  , 
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,           
 ---(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) margin,           
 ---(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,           
 ---(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where          
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice <>1                               
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID  
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid,
  ihdepartmentid,     
 ihdepexrate, ihexchangerate

 
       
 ------ --gave idratetype condition for special invoice return          
 ------ --special invoice return - cash          
 ------ select           
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),           
 ------  sum(idunitprice )) cashsales, convert(numeric(18,8),           
 ------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,8),           
 ------  sum(idunitprice * ihexchangerate)) ccashsales,          
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,           
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
 ------  (convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,           
 ------  (convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
 ------  (convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,0.00,0.00,0.00,0.00,0.00,0.00,
 ------  departmentname, ihdepartmentid departmentid         
 ------ ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 ------ from           
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d           
 ------ where           
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and           
 ------  ihdepartmentid =d.departmentid and idratetype=0 and ihproforma=0 and           
 ------  ihshopid = shopid and ihcashinvoice=1 and ihTransfinished = 1          
 ------ group by           
 ------  shopname, ihshopid, departmentname, ihdepartmentid,           
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid          
 ------ union all         
  
 ------ --special invoice return - credit          
 ------ select           
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,           
 ------  0.0 ccashsales, convert(numeric(18,8), sum(idunitprice )) creditsales,           
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate)) dcreditsales,           
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate)) ccreditsales,           
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,          
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,          
 ------  convert(numeric(18,8), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,        
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,           
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate) - sum(idcostprice*reqqty) * ihexchangerate) cmargin,           
 ------  0.00,0.00,0.00,0.00,0.00,0.00,departmentname, ihDepartmentId departmentid           
 ------ ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 ------ from           
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,           
 ------  adepartmentmaster d           
 ------ where           
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and           
 ------  idratetype=0 and ihproforma=0 and ihshopid = shopid and           
 ------  ihcashinvoice=0 and ihDepartmentId = d.departmentid          
 ------  and ihTransfinished = 1          
 ------ group by           
 ------  shopname, ihshopid, ihdepartmentid, departmentname, ihinvoicedate ,           
 ------  ihexchangerate, ihdepexrate,ihInvoiceid          
                   
 ------union all          
 ------ --gave idratetype condition for special invoice return          
 ------ --special invoice return - cash          
 ------ select           
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),           
 ------  -(sum(idunitprice ))) cashsales, convert(numeric(18,8),           
 ------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,8),           
 ------  -(sum(idunitprice * ihexchangerate))) ccashsales,           
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(idcostprice * abs(reqqty)) costvalue,           
 ------  sum(idcostprice * abs(reqqty)) * ihdepexrate dcostvalue, sum(idcostprice * abs(reqqty)) *           
 ------  ihexchangerate ccostvalue,  -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,           
 ------  0.00,0.00,0.00,0.00,0.00,0.00,departmentname, ihdepartmentid departmentid           
 ------ ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 ------ from           
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d           
 ------ where           
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0            
 ------  and ihproforma=0 and ihshopid = shopid and ihTransfinished = 1           
 ------  and ihcashinvoice=1 AND IDratetype=1 and           
 ------  ihdepartmentid = d.departmentid           
 ------ group by           
 ------  shopname, ihdepartmentid, departmentname, ihshopid,           
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid     
          
 ------union all          
 ------ --special invoice return - credit          
 ------ select           
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
 ------  -(convert(numeric(18,8), sum(idunitprice ))) creditsales,           
 ------  -(convert(numeric(18,8), sum(idunitprice * ihdepexrate))) dcreditsales,           
 ------  -(convert(numeric(18,8), sum(idunitprice * ihexchangerate))) ccreditsales,           
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,           
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
 ------  -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8),           
 ------  sum(idunitprice ))) -  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,           
 ------  0.00,0.00,0.00,0.00,0.00,0.00,departmentname, ihdepartmentid departmentid           
 ------ ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 ------ from           
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,           
 ------  adepartmentmaster d           
 ------ where           
 ------  ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND           
 ------  IHCANCELLED = 0 and ihproforma = 0 and ihshopid = shopid and           
 ------  ihcashinvoice = 0 and idratetype = 1 and ihtransfinished = 1 and           
 ------  ihdepartmentid = d.departmentid           
 ------ group by           
 ------  shopname, ihshopid, ihdepartmentid, departmentname,          
 ------  ihinvoicedate , ihexchangerate, ihdepexrate,ihInvoiceid          

-- RefNo-3 ends
           
 union all          
           
  select           
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,0.00,0.00,0.00,  
   -sum(grncostprice*grndquantity) costvalue, - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,           
   -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,           
   
   - --(convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) - sum(grncostprice*grndquantity)) margin,
   - --(convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) - sum(grncostprice*grndquantity))* grnhdepexRate dmargin,
   - --(convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) - sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,           
   
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))))-  
           sum(grncostprice*grndquantity)) margin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -                   
       sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -  
        sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,                   
   0.00,0.00,0.00,
   -convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) GReturn,           
   -convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0))) * grnhdepexRate) dGReturn,           
   -convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0))) * grnhExchangeRate) cGReturn,
   departmentname, grnhdepartmentid departmentid          
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
  ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,
   convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount
  from           
   losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d           
  where           
   GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0           
   and grnhshopid = shopid and grnhdepartmentid = d.departmentid           
  group by           
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,           
   grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID          

  --hari added to include the service booking invoice parts replaced items          
 UNION ALL          
 
  --service invoice (cash) 
  select           
   shopname, repinvdshopid, serinvhdate, 
   --convert(numeric(18,8),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))) cashsales,
   --convert(numeric(18,8),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))* seinvhdepexrate) dcashsales,          
   --convert(numeric(18,8),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate) ccashsales,          
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcashsales,            
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccashsales,            

   0.0 creditsales, 0.0 dcreditsales , 0.0 ccreditsales ,
   sum(repinvdcostprice * repinvdqty) costvalue,           
   sum(repinvdcostprice * repinvdqty) * seinvhdepexrate  dcostvalue,           
   sum(repinvdcostprice * repinvdqty) *serinvhcmpexrate ccostvalue,           
   
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),           
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,          
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty)margin,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate dmargin,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate cmargin,            
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, serinvhDepartmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2

 --RefNo-4  start commneted, since this gst amount is taken care in below
  --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount
  --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,
  --convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount
    ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
--RefNo-4 ends
  from           
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d           
  where           
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0           
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1          
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0        
  group by           
   shopname, repinvdshopid, serinvhDepartmentid,           
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid           
          
 union all          
 
 --service Details (cash)      
  select           
   shopname, serinvhshopid, serinvhdate,
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0))cashsales ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate)dcashsales ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate)ccashsales ,           
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate)dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate)ccashsales ,             
   
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,               
   0 costvalue, 0 dcostvalue, 0 ccostvalue,           
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)),           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) *  serinvhcmpexrate) ,           
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ,             
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, serinvhDepartmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount
  ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,
   convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount
  from           
--RefNo-4 start commented below
  -- losserviceinvheader, ashops s, adepartmentmaster d           
  --where           
  -- serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1          
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid     
losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid   and Patindex('%y%',repinvdtype)>0 
 where                   
	serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1  
    and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-4 ends 
 
 union all

  --service invoice (credit)        
  select           
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
   sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*           
   seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,           
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * seinvhdepexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate,  
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, serinvhDepartmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  --RefNo-4  start commneted, since this gst amount is taken care in below
  --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount
  --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,
  -- convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount
    ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
    --RefNo-4  ends
  from           
   losinvoicedpartsreplacedetails, losserviceinvheader,           
   ashops s, adepartmentmaster d 
  where 
	serinvhid = repinvinvoiceid and           
    serinvhshopid = repinvdshopid AND serinvhcancelled=0           
    and repinvdshopid = shopid and serinvhcashacc is null           
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid            
   and Patindex('%y%',repinvdtype)>0        
  group by           
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,          
   serinvhcmpexrate ,serinvhid           
  
  union all          
  
--  --service Details          
  select           
   shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) creditsales ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate) dcreditsales ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate) ccreditsales ,           
   convert(numeric(18,8),serinvhserviceamt- (isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) creditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
   0 costvalue, 0 dcostvalue, 0 ccostvalue,           
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))*seinvhdepexrate) ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))*serinvhcmpexrate) ,           
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*seinvhdepexrate) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*serinvhcmpexrate) ,             
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, serinvhDepartmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount
  ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,
  convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount
from  
   --RefNo-4 start commented below         
  -- losserviceinvheader, ashops s, adepartmentmaster d           
  --where           
  -- serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0          
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid      
  losserviceinvheader
	  inner join  ashops s on serinvhshopid = shopid 
	  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
	  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
	  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
	  and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0 
 where                   
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-4 ends

  union all          
         
  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002          
  --credit          
 
  select           
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,           
   0.0 ccashsales,          
   convert(numeric(18,8), sum(redunitprice)) creditsales,           
   convert(numeric(18,8), sum(redunitprice * rehdepexrate))  dcreditsales, 
   convert(numeric(18,8), sum(redunitprice * rehexchangerate)) ccreditsales, sum(redcostprice * redquantity) costvalue,           
   sum(redcostprice * redquantity) * rehdepexrate dcostvalue, sum(redcostprice * redquantity) *           
   rehexchangerate ccostvalue,  (convert(numeric(18,8), sum(redunitprice ))) -           
   sum(redcostprice * redquantity) margin, (convert(numeric(18,8), sum(redunitprice * rehdepexrate))) -           
   sum(redcostprice * redquantity) * rehdepexrate dmargin,(convert(numeric(18,8),           
   sum(redunitprice * rehexchangerate))) - sum(redcostprice * redquantity) * rehexchangerate cmargin,           
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, rehdepartmentid          
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,0.0 GSTAmount ,0.0 dGSTAmount,0.0 cGSTAmount
  from           
   losExportDetail, losExportHeader, ashops s, adepartmentmaster d           
  where           
   rehExportID = redExportID and rehshopid = redshopid AND           
   reHCANCELLED=0 and rehtype ='i' and          
   rehproforma=0 and rehshopid = shopid and rehcashinvoice=0 and           
   rehdepartmentid = d.departmentid           
  group by           
   shopname, rehshopid, departmentname, rehdepartmentid, rehExportDate,           
   rehdepexrate, rehexchangerate,rehExportID           
          
 union all          
 -- added From Vwcashsales -Margin Not calculating          
           
 select           
  s.shopname, vws.sishopid, vws.siinvoicedate,           
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,           
  --convert(numeric(18,8),sum(vws.siamount * aidepexrate)) as  dcashsales,           
  --convert(numeric(18,8),sum(vws.siamount * aiexchangerate)) as ccashsales,  
  convert(numeric(18,8),sum(vws.sidamount)) as  dcashsales,  
  convert(numeric(18,8),sum(vws.sicamount)) as ccashsales,   
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,           
   0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,          
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,           
  --convert(numeric(18,8),sum(vws.siamount * aidepexrate)) as  dcashsales,           
  --convert(numeric(18,8),sum(vws.siamount * aiexchangerate)) as ccashsales, 
  convert(numeric(18,8),sum(vws.sidamount))as  dmargin,  
  convert(numeric(18,8),sum(vws.sicamount))as cmargin,  
  0.00,0.00,0.00,0.00,0.00,0.00,d.departmentname,lah.aidepartmentid  departmentid           
 ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 , sum(vws.GSTAmount)as GSTAmount
 , sum(vws.dGSTAmount)as dGSTAmount
 , sum(vws.cGSTAmount)as cGSTAmount
 from           
  vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d ,ashops s          
 where           
  aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and           
  aishopid = sishopid and lah.aicashinvoice=1 and           
  lah.aidepartmentid =d.departmentid and s.departmentid = d.departmentid          
  and aiShopId = s.ShopId          
 group by           
  s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid, vws.siinvoicedate          
          
 union all          
          
    select s.shopname, vws.sishopid, vws.siinvoicedate,           
    0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,           
    convert(numeric(18,8),sum(vws.siamount)) as  creditsales,           
    --convert(numeric(18,8),sum(vws.siamount * aidepexrate)) as   dcreditsales,           
    --convert(numeric(18,8),sum(vws.siamount * aiexchangerate)) as ccreditsales,  
    convert(numeric(18,8),sum(vws.sidamount)) as  dcashsales,  
	convert(numeric(18,8),sum(vws.sicamount)) as ccashsales,   
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,          
    convert(numeric(18,8),sum(vws.siamount)) as  margin,           
    --convert(numeric(18,8),sum(vws.siamount * aidepexrate)) as   dmargin,           
    --convert(numeric(18,8),sum(vws.siamount * aiexchangerate)) as cmargin,          
    convert(numeric(18,8),sum(vws.sidamount))as dmargin,  
    convert(numeric(18,8),sum(vws.sicamount))as cmargin,  
    0.00,0.00,0.00,0.00,0.00,0.00,d.departmentname,lah.aidepartmentid  departmentid           
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
    , sum(vws.GSTAmount)as GSTAmount
     , sum(vws.dGSTAmount)as dGSTAmount
	 , sum(vws.cGSTAmount)as cGSTAmount
    from vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d,ashops s          
    where aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and           
    aishopid = sishopid and lah.aicashinvoice=0 and lah.aidepartmentid =d.departmentid          
    and s.departmentid = d.departmentid and s.ShopId = aiShopId group by               
    s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid,vws.siinvoicedate,aiinvoiceid           
           
    UniOn All -- added from vwCashSales         
    --Shop debit credit notes and handling debit notes which are debit to the        
    -- customer and hence act as invoices to be settled              
    Select  s.shopname,losdcnshopid,losdcndate,      
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,          
    COnvert(numeric(18,8),Sum(losDCNAmount))  creditsales,             
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dcreditsales,       
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  ccreditsales,       
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                   
    COnvert(numeric(18,8),Sum(losDCNAmount))  margin,             
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dmargin,       
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  cmargin,      
    0.00,0.00,0.00,0.00,0.00,0.00,d.departmentname,losdcndepartmentid           
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
     ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount
    From Ashops s,  losdebitcreditnote, adepartmentmaster d       
    Where  s.shopid = losdcnshopid And s.accountable Is Not Null           
    And d.DepartmentID = losdcndepartmentid And losdcncancelled =0            
    And losdcndebit =1  Group By s.shopname,d.departmentname,losdcnshopid,          
    losdcndate, losdepexrate, losexchangerate,losdcndepartmentid      
      
    --hq serivce invoice dOne for shop            
    Union all      
       
    Select  null, 0,ai.invoicedate,      
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,          
	COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,               
	COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,         
	COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)ccreditsales,         

    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                   
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,             
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,       
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)) * exchangerate)cmargin,      

    0.00,0.00,0.00,0.00,0.00,0.00,d.departmentname,ai.departmentid   
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
    ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount 
    ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,
     convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount

    From accountsinvoiceheader ai, serviceinvoicedetails ser ,adepartmentmaster d       
    Where ai.invoiceid = ser.invoiceid And ai.companyid =             
    ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0     
    and ai.departmentid = d.departmentid and ai.companyid = d.companyid       
    Group By  ai.invoicedate,depexrate,exchangerate,      
    d.departmentname,ai.departmentid          
          
 ) cashcreditcollection          
group by           
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,           
 cashcreditcollection.departmentname, cashcreditcollection.departmentid,           
 cashcreditcollection.poshbilldate          
          

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO
/****** Object:  View [dbo].[vwHqPurchaseOrder]    Script Date: 05/28/2011 13:06:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchaseOrder]'))
BEGIN
DROP VIEW vwHqPurchaseOrder
END
GO
  
/*  
Altered By Sreejith  
Altered on 20100724  
Added the left outer join with the function [dbo].[fnHQPurchaseorder]()  
*/  
------------------------------------------  
--RefNo : 01  
--Modified By : VinothMurugan V.  
--Modified Date : 30/07/2010  
--Purpose : adding priority and type  
------------------------------------------  
--Altered by SReejith  
--Altered on 20100818  
--Added  h.pohvendorid and h.pohDepartmentid fileds into the view  
--Already there was a column for vendorid from vwvendorItemDescription(Will be null in the cases if item does'nt exist)  
--So Added  h.pohvendorid also into the view for using in the report rptPurchaseOrderVendorWiseDetail  
--------------------------------------------  
--Altered by Abhishek CS  
--Altered on 20100914  
--Added  vwitemdescription for item description  
---------------------------------------------------------  
--RefNo:02  
--Modified by : VinothMurugan V  
--Date    : 06/10/2010  
--purpose   : Adding Other Charge Amount for kooddoo  
---------------------------------------------------------  
--Modified By : Sreejith  
--Modified on : 20101105  
--Comment : added tow fields : pohcmpexrate,pohdepexrate,pohSingleItemCatChecked,pohSingleItemCatId  
---------------------------------------------------------  
--Modified By : Nidheesh P V  
--Modified on : 20101105  
--Comment : added podItemTaxPercentage,podItemTaxAmount,podItemTaxCategory 
---------------------------------------------------------  
--Ref.No.1
--Modified By : AADYAKUMAR.D.V  
--Modified on : 02/08/2012  
--Comment     : Wathaniya need to show Purchase Request Number in 
--              Purchase Order preview    
---------------------------------------------------------  
--Ref.No.2
--Modified By : Shine Das
--Modified on : 04/08/2012  
--Comment     : Wathaniya need to Purchase Requested Person in report.
-- So userid also added. 
---------------------------------------------------------  
create VIEW [dbo].[vwHqPurchaseOrder] AS  
select  distinct h.pohDepartmentid,h.pohtype,h.pohPoid,h.pohpono,h.pohPodate,a.itemid,h.pohSupAddr,
h.pohdeliveryaddr,h.pohRefNo,h.pohremarks,  
p.podDetailID,p.podQty,p.podUnitPrice,  
p.poddescription ,s.vendorname,dm.departmentname, apt.packingtypename,  
ac.address1,ac.address2,cur.Symbol,  
v.packunitcode,  
--vw.itemdescription,  
vwi.itemdescription,  
vw.code,vw.vendorid,h.pohshipmentmode,h.pohpaymentmode, h.pohvendorid,  
convert(varchar(250),h.pohDeliveryTerms)pohdeliveryterms, h.pohProjectStartDate,  
h.pohProjectEndDate, h.pohProjectOtherInfo,h.pohCustomDutyByCustomer,h.pohTransportation,h.pohcancel ,  
fn.PreviousPO as PreviousPurchaseorder,fn.SupplierName as PreviousSupplier,  
a.itemrate LastItemRate,lp.priority,lt.type,  
sum( o.POAmount) POAmount,h.pohcmpexrate,h.pohdepexrate,h.pohSingleItemCatChecked,h.pohSingleItemCatId,    --RefNo:02  
podItemTaxPercentage,podItemTaxAmount,podItemTaxCategory,Q.pohpono Quatation,PR.pohpono PurchaseRequest
,h.pohuserid  --Ref.No.2
FROM lopurchaseorderheader h
--Ref.No.1---START---
left outer join lopurchaseorderheader Q on Q.pohtype='Q' 
and Q.pohPoid=H.pohquotationid
and Q.pohdepartmentid=h.pohdepartmentid
left outer join lopurchaseorderheader PR on PR.pohtype='R' 
and PR.pohPoid=Q.pohquotationid
and PR.pohdepartmentid=Q.pohdepartmentid
--Ref.No.1----END----
------------------------------------------------RefNo:02
left outer JOIN  loPurchaseOrderOthCharge o ON
o.POorderID  = h.pohPoid
----------------------------------------------
left outer join lostype as lt on lt.Typeid=h.pohTypeid --RefNo : 01
left outer join  lospriority lp on h.pohpriorityid = lp.priorityid --RefNo : 01
left outer join adepartmentmaster dm on  h.pohrequestdepartment=dm.departmentid
,vwpackingtype v,aitem a,apackingtype apt, vwItemDescription vwi,
avendormaster s ,acompanymaster ac,aCurrencyMaster cur,vwvendorItemDescription vw ,lopurchaseorderdetail p
left outer join [dbo].[fnHQPurchaseorder]() as Fn on itemid= p.poditemid and PurReqNo= p.podpoid
where p.poditemid=a.itemid and p.podpackingtypeID=v.packingtypeid and a.unitsid=v.unitsid
and h.pohpoid=p.podpoid and h.pohVendorID = s.VendorID and h.pohcompanyid = ac.CompanyID and p.podpackingtypeid=apt.packingtypeid  
and  s.CurrencyID = Cur.CurrencyID and vw.itemid=a.itemid and (h.pohVendorID=vw.vendorid or vw.vendorid is null)
and a.itemid=vwi.ItemID
-----------------------------------------------------------RefNo:02
group by
h.pohDepartmentid,h.pohtype,h.pohPoid,h.pohpono, h.pohPodate,a.itemid,h.pohSupAddr,
h.pohdeliveryaddr, h.pohRefNo , h.pohremarks,p.podDetailID, p.podQty , p.podUnitPrice,
p.poddescription ,s.vendorname,dm.departmentname, apt.packingtypename,ac.address1,ac.address2,cur.Symbol,v.packunitcode,vwi.itemdescription,  
vw.code,vw.vendorid,h.pohshipmentmode,h.pohpaymentmode, h.pohvendorid,
h.pohdeliveryterms, h.pohProjectStartDate,  
h.pohProjectEndDate, h.pohProjectOtherInfo, h.pohCustomDutyByCustomer, h.pohTransportation,h.pohcancel ,  
fn.PreviousPO, fn.SupplierName,
a.itemrate,lp.priority,lt.type,h.pohcmpexrate,h.pohdepexrate,h.pohSingleItemCatChecked,h.pohSingleItemCatId
,podItemTaxPercentage,podItemTaxAmount,podItemTaxCategory
,Q.pohpono,PR.pohpono
,h.pohuserid  --Ref.No.2
---------------------------------------------------------  
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwCAshSalesGSTSeparately')
   DROP view dbo.vwCAshSalesGSTSeparately
GO
  

-- Modified On          : 21/06/2004      
-- Modified by          : Hariharan R, Vekitesh , Aneesh      
-- Comments             : added Goods return Case      
--   : added utility bills And corrected amount column for dep in room billing      
--   : Other charges given in Group Byclause to avoid doubling in Invoice queries      
--   : corrrected order of goods return note amount selecitOn      
--   : Shop debit credit note query added   
-------------------------------------------------------------------------------------------  
--Modified by           : Bijesh.B as on 07/06/2011  
--            : RefNo-1  
--Comments              : Since Post Dated Cheque (Fully/Partially) option was included   
--        in POS(Sonee) interface,the difference between 'BILL AMOUNT' and   
--        PD Cheque Amount is the actual Cash Sales      
--Backup                : vwCAshSalesAsOn07062011   
------------------------------------------------------------------------------------------           
-- Modified by : Bijesh.B  
-- Date        : 17/06/2011, 04/07/2011  
-- RefNo       : RefNo-2   
-- Comments    : PD Cheque feature added      
------------------------------------------------------------------------------------------           
-- Modified by : Bijesh.B  
-- Date        : 03/07/2011  
-- RefNo       : RefNo-3   
-- Comments    : Removed the link from ahqPostDatedChequeDetails  
--               Need to show 'pd cheque amount' even if it is not registered     
------------------------------------------------------------------------------------------           
-- Modified by : Bijesh.B  
-- Date        : 28/07/2011  
-- RefNo       : RefNo-4   
-- Comments    : Bugsheet - Spl Invoice amount is wrongly updated in cash sales,  
------------------------------------------------------------------------------------------           
-- RefNo        : RefNo-5   
-- Modified by  : Bijesh.B  
-- Date         : 19/08/2011  
-- Ticket Id    : JSZ-828136 (SHEESHA)  
-- Description  : Need UserWise selection for Cash Denomination interface  
--              : UserID column included in all query   
------------------------------------------------------------------------------------------  
-- RefNo        : RefNo-6   
-- Modified by  : AADYAKUMAR D V
-- Date         : 21/01/2012  
-- Description  : Added F&B part 
------------------------------------------------------------------------------------------          
----------------------------------------------------------------------------------------------       
--RefNo        : New View (copy of vwCAshSales)
--Created by   : Bijesh.B 
--Date         : 11/04/2012
--Ticket id    : JDJ-400367 
--Comments     : new reports (rtdailysalescollectionshopwiseGSTSeparately,
--				 rptdailysalescollectiondepwiseGSTSeparately)    for sonee - GST separation)
----------------------------------------------------------------------------------------------       
--RefNo         : RefNo-7
--Modified by   : Bijesh.B 
--Date          : 13/07/2012
--Ticket id     : JDJ-400367 
--Desc          : correct values
----------------------------------------------------------------------------------------------       
--RefNo         : RefNo-8
--Modified by   : Bijesh.B 
--Date          : 16/07/2012
--Ticket id     : JDJ-400367 
--Desc          : correctd values
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-9
--Date         : 03/08/2012  
--Comments     : Corrected Other Charges Service Tax in Credit Invoice
----------------------------------------------------------------------------------------------       

create View vwCAshSalesGSTSeparately As    
    Select poshcompanyid As companyid, poshshopid As shopid, poshbilldate As billdate,       
    poshcAshaccid As accountid, 
    --COnvert(numeric(18,8), Sum(posdunitprice))  As amount,      
    --COnvert(numeric(18,8), Sum(posdunitprice)* poshdepexrate)  As damount,      
    --COnvert(numeric(18,8), Sum(posdunitprice)* poshexchangerate) As camount,      
	convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) amount, 
	convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) damount,
	convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) camount,

    1 As cAsh, 'p' As transtype, poshdepartmentid departmentid ,0 as PdChqCancelled  
    ,ISNULL(poshUserId,0) as UserID   
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount
  
    From  losposheader ph,losposdetail pd   Where       
    ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0       
    and isnull(ph.PosPostDate,0)<>1  
    Group By poshcompanyid , poshshopid , poshbilldate ,poshbillid, poshcAshaccid ,       
    poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate,ISNULL(poshUserId,0)      
UNION ALL  
    --RefNo-1  
    --FULL PD CHEQUE 
    Select poshcompanyid As companyid, ph.poshshopid As shopid, poshbilldate As billdate,       
 poshcAshaccid As accountid,  
 --Convert(numeric(18,8),(ph.poshBillAmount - PDCheque.PosBankAmount)) as amount,   
 --Convert(numeric(18,8),(ph.poshBillAmount - PDCheque.PosBankAmount) * poshdepexrate)  As damount,      
 --Convert(numeric(18,8), (ph.poshBillAmount - PDCheque.PosBankAmount) * poshexchangerate) As camount,    

-- convert(numeric(18,8),sum(posdunitprice)-pdCheque.PosBankAmount) amount,   
-- convert(numeric(18,8),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) damount,   
-- convert(numeric(18,8),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) camount,  
	convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) amount, 
	convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) damount,
	convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) camount,

  0 As cAsh, 'PD CHEQUE' As transtype, poshdepartmentid departmentid, 0 as PdChqCancelled      
  ,ISNULL(poshUserId,0) as UserID  
     ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount

 From  losposheader ph,losposdetail pd,losPosChequeDetails PDCheque  
 Where       
 ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0       
 and isnull(ph.PosPostDate,0)=1   
 and PDCheque.PoshBillID = ph.poshBillID and PDCheque.PoshShopID = ph.poshShopID  
 Group By poshcompanyid , ph.poshshopid , poshbilldate ,ph.poshbillid, poshcAshaccid ,       
 poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate ,  
 PDCheque.PosBankAmount,ISNULL(poshUserId,0)  
    
UniOn All      

Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,       
	--COnvert(numeric(18,8),Sum(sedunitprice)) As amount,      
	--COnvert(numeric(18,8),Sum(sedunitprice) * sehdepexrate) As damount,      
	--COnvert(numeric(18,8),Sum(sedunitprice) * sehexchangerate) As camount,      
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0)))) amount,
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) damount,
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) camount,
    1,'e'  As transtype, sehdepartmentid departmentid,0 as PdChqCancelled  
    ,ISNULL(sehUserID,0) as UserID           
    ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
    convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount
    From  losposexchangeheader ph, losposexchangedetail pd       
    Where ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid And       
    sehcancelled=0 And sedbillorexchange ='E'     
    Group By sehcompanyid,sehshopid, sehexchangedate, sehexchangeid,    
    sehcAshaccid, sehdepartmentid, sehdepexrate, sehexchangerate,ISNULL(sehUserID,0)       
  
Union All      
   
--RefNo-4 start   
-- commented below   
/*  
Select       
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,       
 COnvert(numeric(18,8),Sum( vw.idunitprice ))  As amount,      
 COnvert(numeric(18,8),Sum( vw.idunitprice) * ihdepexrate)  As damount,      
 COnvert(numeric(18,8),Sum( vw.idunitprice) * ihexchangerate)  As camount,      
 1, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled      
From       
 losspecialinvoiceheader ih, vwShopSplInvItemAmount vw       
Where       
 ih.ihshopid = vw.idshopid And ih.ihinvoiceid = vw.idinvoiceid And       
 ihcancelled=0 And ihcAshinvoice =1 And ih.ihproforma =0 And ihtransfinIshed=1      
Group By    
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
 ihdepexrate, ihexchangerate  
  
UniOn All      
  
--direct invoice      
Select       
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,       
 COnvert(numeric(18,8),Sum(idunitprice) ) As amount,       
 COnvert(numeric(18,8),Sum(idunitprice) * ihdepexrate) As damount,       
 COnvert(numeric(18,8),Sum(idunitprice) * ihexchangerate) As camount,       
 0 ihcAshinvoice, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled      
From       
 losspecialinvoiceheader ih, vwShopSplInvItemAmount invd       
Where       
 ih.ihshopid = invd. idshopid And ih.ihinvoiceid = invd.idinvoiceid And       
 ihcancelled=0 And ihcAshinvoice =0 And ih.ihproforma =0 And ihTransfinIshed =1      
Group By    
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,       
 ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate   
*/  
   
-- special Invoice (cash)    
select                                   
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,             
 --convert(numeric(18,8),sum(idUnitPrice)) amount,  
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) damount,  
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) camount, 
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) amount,
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) damount,
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) camount, 
                                  
 1, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled     
 ,ISNULL(ihUserId,0) as UserID  
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount

from                                   
 losspecialinvoicedetail, losspecialinvoiceheader                                   
where          
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                  
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0                              
Group By    
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
 ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0)  
                               
union all           
  
-- special invoice - return before despatch                      
select         
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,       
--convert(numeric(18,8),-sum(idUnitPrice)) amount,  
--convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) damount,  
--convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) camount,                                   
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) damount,    
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) camount,     

1, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled     
,ISNULL(ihUserId,0) as UserID  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount

from                                   
 losspecialinvoicedetail,losspecialinvoiceheader                                  
where   
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                   
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1   
 and ihNoofOCDetails<>0                              
Group By    
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
 ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0)  
                                      
union all                                  
                               
-- Special invoice return  - after desp                                
select                                   
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,  
 --convert(numeric(18,8),-sum(idUnitPrice)) amount,  
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) damount,   
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) camount,                                   
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) damount,    
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) camount,   

 1, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled   
 ,ISNULL(ihUserId,0) as UserID  
 ,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount

from                                   
 losspecialinvoicedetail,losspecialinvoiceheader                                  
where            
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                   
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1                                 
Group By    
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
 ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0)   
  
-- special Invoice (credit)  
union all  
  
select                                   
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,             
 --convert(numeric(18,8),sum(idUnitPrice)) amount,  
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) damount,  
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) camount,
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) damount,    
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) camount,  
                                    
 0, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled     
 ,ISNULL(ihUserId,0) as UserID  
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount

from                                   
 losspecialinvoicedetail, losspecialinvoiceheader                                   
where                                   
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                  
 and IhTransFinished = 1 And ihcAshinvoice<>1 and ihNoofOCDetails=0                              
Group By    
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
 ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0)  
                               
union all                                  
  
-- special invoice - return before despatch                      
select         
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,       
--convert(numeric(18,8),-sum(idUnitPrice)) amount,  
--convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) damount,  
--convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) camount,                                   
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) damount,    
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) camount,   

0, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled     
 ,ISNULL(ihUserId,0) as UserID  
 ,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount

from                                   
 losspecialinvoicedetail,losspecialinvoiceheader                                  
where        
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                   
 idratetype = 0 and ihproforma = 0 And ihcAshinvoice<>1 and ihTransFinished = 1   
 and ihNoofOCDetails<>0                              
Group By    
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
 ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0)   
                                      
union all                                  
                               
-- Special invoice return  - after desp                                
select                                   
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,  
 --convert(numeric(18,8),-sum(idUnitPrice)) amount,  
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) damount,   
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) camount,                                   
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)damount,    
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)camount,     
 
 0, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled   
,ISNULL(ihUserId,0) as UserID  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount

from                                   
 losspecialinvoicedetail,losspecialinvoiceheader                                  
where            
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                   
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice<>1                                 
Group By    
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
 ihdepexrate, ihexchangerate,ISNULL(ihUserId,0)  
--RefNo-4 ends   
  
UniOn All      
      
    Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,       
    --COnvert(numeric(18,8),-Sum(sedunitprice)) As amount,       
    --COnvert(numeric(18,8),-Sum(sedunitprice) * sehdepexrate) As damount,      
    --COnvert(numeric(18,8),-Sum(sedunitprice) * sehexchangerate) As camount, 
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) amount,
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) damount,
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) camount,

   1, 'e' As transtype, sehdepartmentid  departmentid ,0 as PdChqCancelled    
   ,ISNULL(sehUserID,0) as UserID
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
    convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount

    From   losposexchangeheader ph, losposexchangedetail pd      
    Where ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid       
    And sehcancelled=0 And sedbillorexchange ='B' And sedexchangeqty > 0      
    Group By sehcompanyid, sehshopid, sehexchangedate, sehexchangeid, sehcAshaccid,       
    sehdepartmentid, sehdepexrate, sehexchangerate,ISNULL(sehUserID,0)  
      

    UniOn All      

    Select ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,       
 --   Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
 --	(Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0))     
 --		Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))  End Amount,       
 --Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
 --	(Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0)) * ihdepexrate    
 --	Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))* ihdepexrate  End DAmount,       
 --   Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
 --    (Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0)) * ihExchangeRate     
 --   Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))* ihExchangeRate End cAmount,     

	Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
		(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0))     
			Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))  End Amount,       
	Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
		(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0)) * ihdepexrate    
		Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))* ihdepexrate  End DAmount,       
    Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	    (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0)) * ihExchangeRate     
    Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))* ihExchangeRate End cAmount,     

	1,'c' As transtype, ih.ihdepartmentid  departmentid ,0 as PdChqCancelled    
    ,ISNULL(ihuserid,0) as UserID    
	,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,
	convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount

    From  losinvoiceheader ih Left Outer Join losinvoicedetail invd On ih.ihshopid = invd.idshopid      
    And ih.ihinvoiceid = invd.idinvoiceid  Left Outer Join      
    (Select ioShopID,ioInvoiceID,Sum(ioAmount) ioAmount From losInvoiceOC       
    Group By   ioShopID,ioInvoiceID) ocd  On ihshopid= ocd.ioShopid And     
    ihinvoiceid=ocd.ioInvoiceID, Ashops s   Where       
    ihcancelled=0 And ihcAshinvoice = 1 And ih.ihproforma =0 And ih.ihtype='I'      
     And ihshopid = s.shopid And ihcompanyid = s.COmpanyid      
    Group By ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid,     
    ihdepartmentid,  ihdepexrate, ihexchangerate, ocd.ioAmount, s.futurevarchar,  
     ih.ihdutypaidby,ISNULL(ihuserid,0)  
    
  
UniOn All      
      
Select       
 vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,       
 COnvert(numeric(18,8),(vws.siamount )) As amount,       
 COnvert(numeric(18,8),(vws.siamount) * aidepexrate) As damount,      
 COnvert(numeric(18,8),(vws.siamount) * aiexchangerate) As camount,      
 lah.aicAshinvoice , 's' As transtype, aidepartmentid departmentid ,0 as PdChqCancelled      
,ISNULL(vws.UserID,0) as UserID   
, (vws.GSTAmount)as GSTAmount
, (vws.dGSTAmount)as dGSTAmount
, (vws.cGSTAmount)as cGSTAmount
From       
 vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah, vwshops s      
Where       
 s.shopid = aIshopid And aiinvoiceid=siinvoiceid And aicancelled=0 And       
 aiproforma=0 And aIshopid = sIshopid And lah.aicAshinvoice =1   
      
UniOn All      
--hq serivce invoice dOne for shop      
Select       
 ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,       
 --COnvert(numeric(18,8),Sum(serviceqty * amount) ),      
 --COnvert(numeric(18,8),Sum(serviceqty * amount) *depexrate),      
 --COnvert(numeric(18,8),Sum(serviceqty * amount) *exchangerate),      

COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  amount,             
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)damount,       
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)camount,       
 
 1 ,'hs', ai.departmentid  departmentid  ,0 as PdChqCancelled      
 ,ISNULL(ser.UserID,0) as UserID 
  ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount 
 ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,
  convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount

From       
 accountsinvoiceheader ai, serviceinvoicedetails ser       
Where       
 ai.invoiceid = ser.invoiceid And ai.companyid =       
 ser.companyid And ai.cAshinvoice = 1 And ai.cancelled = 0 And ai.proforma = 0       
Group By     
 ai.companyid, ai.invoicedate,ai.invoiceid,ai.exchangerate,ai.bankcAshid,       
 ai.departmentid, depexrate, exchangerate ,ISNULL(ser.UserID,0)  
      
UniOn All      
      
-- hari included From credit sales to correct the daily sales Summary report      

--RefNo-9 start commented and added
--Select       
-- ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,       
-- Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
-- (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0)) -- +Isnull(Sum(invd.idcdcustcur),0)      
-- Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))  End Amount,       
-- Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
-- (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0)) * ihdepexrate --  +Isnull(Sum(invd.idcdcustcur),0)      
-- Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))* ihdepexrate  End DAmount,       
-- Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
-- (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0)) * ihExchangeRate -- +Isnull(Sum(invd.idcdcustcur),0)      
-- Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))* ihExchangeRate End cAmount,       
-- 0 ihcAshinvoice, 'c' As transtype, ih.ihdepartmentid  departmentid ,0 as PdChqCancelled    
--,ISNULL(ihuserid,0) as UserID  
--,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
--,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,
--convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount
 
--From       
-- losinvoiceheader ih       
-- Left Outer Join losinvoicedetail invd       
-- On ih.ihshopid = invd.idshopid And ih.ihinvoiceid = invd.idinvoiceid      
-- Left Outer Join       
-- (Select      
--  ioShopID,ioInvoiceID,Sum(ioAmount) ioAmount      
-- From      
--  losInvoiceOC       
-- Group By     
--  ioShopID,ioInvoiceID) ocd       
-- On ihshopid= ocd.ioShopid And ihinvoiceid=ocd.ioInvoiceID, Ashops s  
--Where       
-- ihcancelled=0 And ihcAshinvoice =0 And ih.ihproforma =0 And ih.ihtype='I'      
-- And ihshopid = s.shopid And ihcompanyid = s.COmpanyid      
--Group By   
-- ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,       
-- ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate, ocd.ioAmount,       
-- s.futurevarchar, ih.ihdutypaidby,ISNULL(ihuserid,0)           

 --credit invoice(Excluding Other charges)
Select       
 ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,       
 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) 
 Else 
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))  
 End Amount,       
 
 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihdepexrate 
 Else
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))* ihdepexrate  
 End DAmount,       
 
 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihExchangeRate
 Else
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))* ihExchangeRate 
 End cAmount, 
       
 0 ihcAshinvoice, 'c' As transtype, ih.ihdepartmentid  departmentid ,0 as PdChqCancelled    
,ISNULL(ihuserid,0) as UserID  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount
 
From       
 losinvoiceheader ih       
 Left Outer Join losinvoicedetail invd       
 On ih.ihshopid = invd.idshopid And ih.ihinvoiceid = invd.idinvoiceid      
 --Left Outer Join       
 --(Select      
 -- ioShopID,ioInvoiceID,Sum(ioAmount) ioAmount      
 --From      
 -- losInvoiceOC       
 --Group By     
 -- ioShopID,ioInvoiceID) ocd       
 --On ihshopid= ocd.ioShopid And ihinvoiceid=ocd.ioInvoiceID
 ,Ashops s  
Where       
 ihcancelled=0 And ihcAshinvoice =0 And ih.ihproforma =0 And ih.ihtype='I'      
 And ihshopid = s.shopid And ihcompanyid = s.COmpanyid      
Group By   
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,       
 ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate,
 s.futurevarchar, ih.ihdutypaidby,ISNULL(ihuserid,0)           

union all

 --Credit Invoice (Other Charges only)
Select       
 ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,       

 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	 convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))              
 Else 
	convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))              
 End Amount,       

Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) 
Else 
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) 
End DAmount,       

Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate) 
Else
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate)
End cAmount,       

0 ihcAshinvoice, 'c' As transtype, ih.ihdepartmentid  departmentid ,0 as PdChqCancelled    
,ISNULL(ihuserid,0) as UserID  
,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihdepexrate)dGSTAmount
,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihexchangerate)cGSTAmount

from losinvoiceheader  ih                  
	left outer join losInvoiceOC ocd  on ihshopid= ocd.ioShopid 
		and ihinvoiceid=ocd.ioInvoiceID         
	,ashops s, adepartmentmaster d                   
where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
group by  
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,       
 ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate,
 s.futurevarchar, ih.ihdutypaidby,ISNULL(ihuserid,0) 

--RefNo-9 ends
      
UniOn All      
      
--serviceinvoice      
Select       
 vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,       
 COnvert(numeric(18,8),vws.siamount) As amount,       
 COnvert(numeric(18,8),vws.siamount * aidepexrate) As damount,       
 COnvert(numeric(18,8),vws.siamount * aiexchangerate) As camount, lah.aicAshinvoice,  
  's' As transtype, lah.aidepartmentid  departmentid ,0 as PdChqCancelled   
,ISNULL(vws.UserID,0) as UserID   
,(vws.GSTAmount)as GSTAmount
,(vws.dGSTAmount)as dGSTAmount
,(vws.cGSTAmount)as cGSTAmount
From       
 vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah      
Where       
 aiinvoiceid=siinvoiceid And aicancelled=0 And aiproforma=0 And aIshopid = sIshopid      
 And lah.aicAshinvoice=0      
      
-- hari included     
 UniOn All      
--hq serivce invoice dOne for shop      
Select       
 ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,       
 --COnvert(numeric(18,8),Sum(serviceqty * amount) ),       
 --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate),      
 --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate),   
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  amount,             
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)damount,       
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)camount,       
0 ,'hs',ai.departmentid  departmentid   ,0 as PdChqCancelled     
,ISNULL(ser.UserID,0) as UserID   
,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount 
,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,
convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount
From       
 accountsinvoiceheader ai, serviceinvoicedetails ser       
Where       
 ai.invoiceid = ser.invoiceid And ai.companyid =       
 ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0       
Group By    
 ai.companyid, ai.invoicedate, ai.invoiceid, ai.exchangerate,ai.bankcAshid,       
 ai.departmentid, depexrate, exchangerate,ISNULL(ser.UserID,0)   
      
-- hari included for service booking advances      
UniOn All      
      
Select       
 serbookhcompanyid, serbookhshopid, serbookadvancedate, serbookhcAshacc,       
 COnvert(numeric(18,8), serbookadvanceamount) ,      
 COnvert(numeric(18,8), serbookadvanceamount * serbookhdepexrate),      
 COnvert(numeric(18,8), serbookadvanceamount * serbookhcmpexrate), 1  ,'sb',       
 serbookhdepartmentid ,0 as PdChqCancelled   
,ISNULL(serbookhUserid,0) as UserID 
,0,0,0  
From LOsServiceBookingHeader      
       
Where       
 serbookhinpcancelled=0       
        And serbookadvanceamount>0      
      
-- hari included for service booking invoices which are cAsh invoices      
UniOn All      
      
Select       
 serinvhcompanyid, serinvhshopid, serinvhdate, serinvhcAshacc,       
 --COnvert(numeric(18,8), serinvhamount) ,       
 --COnvert(numeric(18,8), serinvhamount * seinvhdepexrate) ,       
 --COnvert(numeric(18,8), serinvhamount * serinvhcmpexrate),
 COnvert(numeric(18,8),serinvhamount-isnull(serinvhTaxamount,0)) ,       
 COnvert(numeric(18,8),(serinvhamount-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,       
 COnvert(numeric(18,8),(serinvhamount-isnull(serinvhTaxamount,0)) * serinvhcmpexrate),
 1 , 'sbi',       
 serinvhdepartmentid  ,0 as PdChqCancelled   
,ISNULL(serinvhuserid,0) as UserID   
,convert(numeric(18,8),(isnull(serinvhTaxamount,0)))GSTAmount
,convert(numeric(18,8),(isnull(serinvhTaxamount,0))* seinvhdepexrate)dGSTAmount,
 convert(numeric(18,8),(isnull(serinvhTaxamount,0))* serinvhcmpexrate)cGSTAmount
From       
 losserviceinvheader       
Where       
 serinvhcancelled = 0   And       
 serinvhamount>0 And serinvhcAshacc Is Not Null      
      
-- hari included for service booking invoices which are credit invoices      
UniOn All      
      
Select       
 serinvhcompanyid, serinvhshopid, serinvhdate, serinvhcAshacc,       
 --COnvert(numeric(18,8), serinvhamount),
 --COnvert(numeric(18,8), serinvhamount*seinvhdepexrate),      
 --COnvert(numeric(18,8), serinvhamount * serinvhcmpexrate), 
 COnvert(numeric(18,8),serinvhamount-isnull(serinvhTaxamount,0)) ,       
 COnvert(numeric(18,8),(serinvhamount-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,       
 COnvert(numeric(18,8),(serinvhamount-isnull(serinvhTaxamount,0)) * serinvhcmpexrate),
 0 , 'sbi',       
 serinvhdepartmentid  ,0 as PdChqCancelled   
,ISNULL(serinvhuserid,0) as UserID   
,convert(numeric(18,8),(isnull(serinvhTaxamount,0)))GSTAmount
,convert(numeric(18,8),(isnull(serinvhTaxamount,0))* seinvhdepexrate)dGSTAmount,
 convert(numeric(18,8),(isnull(serinvhTaxamount,0))* serinvhcmpexrate)cGSTAmount

From       
 losserviceinvheader       
Where       
 serinvhcancelled = 0 And       
 serinvhamount>0 And serinvhcAshacc Is null      
      
UniOn All      
      
Select  abh.abhcompanyid, abh.abhshopid,abhBillDate, abh.abhCAshAccId,       
COnvert(numeric(18,8), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,       
COnvert(numeric(18,8), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,       
COnvert(numeric(18,8), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,       
0, 'RBI' type , abh.abhdepartmentid departmentid  ,0 as PdChqCancelled   
,ISNULL(abhUserID,0) as UserID 
,0,0,0  
From       
losApartmentBillHeader abh Where abh.abhCancelled = 0 And abh.abhCAshAccId Is null      
      
UniOn All      
      
Select  abh.abhcompanyid, abh.abhshopid,abhBillDate, abh.abhCAshAccId,       
COnvert(numeric(18,8), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,       
COnvert(numeric(18,8), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,       
COnvert(numeric(18,8), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,       
1, 'RBI' type , abh.abhdepartmentid departmentid ,0 as PdChqCancelled   
,ISNULL(abhUserID,0) as UserID   
,0,0,0
From losApartmentBillHeader abh Where abh.abhCancelled = 0 And abh.abhCAshAccId Is Not Null      
  
UniOn All      
-- UTILITY BILL CREDIT INVOICES       
Select       
 tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhBillDate, tbh.tbhBankCAshID,       
 COnvert(numeric(18,8), Isnull(tbh.tbhAmount,0)) Amount,       
 COnvert(numeric(18,8), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,       
 COnvert(numeric(18,8), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,       
 0, 'UTB' type , tbh.tbhdepartmentid departmentid  ,0 as PdChqCancelled   
,ISNULL(tbhUserID,0) as UserID   
,0,0,0
From       
 losTenantServiceBillHeader tbh, acustomermAster c      
Where       
 tbh.tbhCustomerID=c.customerID And tbh.tbhBankCAshID Is null And      
 tbh.tbhCancelled=0       
      
    UniOn All      
      
-- UTILITY BILL CAsH INVOICES      
    Select tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhBillDate, tbh.tbhBankCAshID,       
    COnvert(numeric(18,8), Isnull(tbh.tbhAmount,0)) Amount,       
    COnvert(numeric(18,8), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,       
    COnvert(numeric(18,8), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,       
    1, 'UTB' type , tbh.tbhdepartmentid departmentid,0 as PdChqCancelled          
    ,ISNULL(tbhUserID,0) as UserID   
    ,0,0,0
    From losTenantServiceBillHeader tbh, acustomermAster c      
    Where  tbh.tbhCustomerID=c.customerID And tbh.tbhBankCAshID Is Not Null And      
    tbh.tbhCancelled=0     
      
    UniOn All      
      
    Select GrnCompanyID, grnhshopid, grnhGoodsReturnNoteDate, grnhCustomerId,       
    -- -COnvert(numeric(18,8),Sum(grndunitprice))  amount,       
    -- -COnvert(numeric(18,8),Sum(grndunitprice) * grnhdepExRate)  damount,      
    -- -COnvert(numeric(18,8),Sum(grndunitprice) * grnhExchangeRate)  camount, 
   -convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) amount,                 
   -convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhdepexRate) damount,                 
   -convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhExchangeRate) camount, 
    0, 'c' As transtype, Grnhdepartmentid  departmentid  ,0 as PdChqCancelled   
    ,ISNULL(grnUserID,0) as UserID   
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,
    -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount
    From losGoodsReturnNoteHeader ih, losGoodsReturnNoteDetail invd       
 Where ih.GrnhShopid = invd.grndshopid And ih.GrnhGoodsreturnnoteID = invd.GrndreturnnoteID      
    And grnhCancel = 0  Group By grncompanyid, grnhshopid, grnhGoodsReturnNoteDate,       
    GrnhGoodsreturnnoteID, grnhCustomerID, grnhdepartmentid, grnhdepExRate, grnhExchangeRate  
    ,ISNULL(grnUserID,0)   
              
    UniOn All    
    --Shop debit credit notes and handling debit notes which are debit to the  
    -- customer and hence act as invoices to be settled        
    Select  losdcnCompanyID, losdcnshopid,losdcndate, losdcncustomerid,    
    COnvert(numeric(18,8),Sum(losDCNAmount))  amount,       
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  damount,      
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  camount,        
    0, 'sdcn' As type , losdcndepartmentid ,0 as PdChqCancelled   
    ,ISNULL(losDCNUserID,0) as UserID   
    ,0,0,0
    From Ashops s, acustomermAster c,     
    losdebitcreditnote Where  s.shopid = losdcnshopid And s.accountable Is Not Null     
    And c.customerid = losdcncustomerid And losdcncustomerid Is Not Null And       
    losdcncancelled =0 And losdcndebit =1  Group By losdcnCompanyID,losdcnshopid,    
    losdcndate, losdcncustomerid,losdepexrate, losexchangerate,losdcndepartmentid   
    ,ISNULL(losDCNUserID,0)  
    
--UNION ALL   
----RefNo-1  
---- PD Cheque only  
--SELECT       
-- poshCompanyID As companyid,PH.poshshopid As shopid, poshbilldate As billdate,       
--    ISNULL(poshChequeAccID,0) As accountid,   
--    Convert(numeric(18,8), CHQ.PosBankAmount)  As amount,      
--    Convert(numeric(18,8), CHQ.PosBankAmount * poshdepexrate)  As damount,   
--    Convert(numeric(18,8), CHQ.PosBankAmount * poshexchangerate) As camount,       
--    0,'PD CHEQUE' As transtype, poshdepartmentid departmentid,0 as PdChqCancelled   
--  ,ISNULL(poshUserId,0) as UserID   
-- FROM   
-- losPosChequeDetails CHQ,LOsPosHeader PH  
-- --, ahqPostDatedChequeDetails PdChqDet  --RefNo-3  
-- WHERE   
--    PH.poshcancelled <> 1 AND --RefNo-2  
-- PH.poshBillID = CHQ.PoshBillID  AND isnull(PH.PosPostDate,0)=1   
-- AND PH.poshShopID = CHQ.PoshShopID  
-- --and PdChqDet.PoshBillID = ph.poshBillID  --RefNo-3  
-- --AND isnull(PdChqDet.Cancel,0)=0          --RefNo-3  
--    Group By poshcompanyid , PH.poshshopid , poshbilldate ,PH.poshbillid, poshcAshaccid ,       
--    poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate,poshChequeAccID,  
--    CHQ.PosBankAmount,ISNULL(poshUserId,0)
--RefNo-6-----------------------------------------------start-----------------------------------------------------------------
   --UNION ALL   
    
   -- Select poshcompanyid As companyid, poshshopid As shopid, dateadd(dd,0, datediff(dd,0, poshbilldate)) As billdate,       
   -- poshcAshaccid As accountid, COnvert(numeric(18,8), Sum( fb_pd_reusedqty*fb_pd_Rate  ))  As amount,      
   -- COnvert(numeric(18,8), Sum( fb_pd_reusedqty*fb_pd_Rate ) * poshdepexrate)  As damount,      
   -- COnvert(numeric(18,8), Sum( fb_pd_reusedqty*fb_pd_Rate ) * poshexchangerate) As camount,      
   -- 1 As cAsh, 'fandb' As transtype, poshdepartmentid departmentid ,0 as PdChqCancelled  
   -- ,ISNULL(poshUserId,0) as UserID     
   -- From  losposfandbheader ph,fb_processdetail pd   Where       
   -- ph.poshshopid = pd.fb_pd_outletid And ph.poshbillid = pd.fb_pd_processid And ph.poshcancelled=0
   -- and poshBillType in ('CA','VO','VCA')        
   -- Group By poshcompanyid , poshshopid , poshbilldate ,poshbillid, poshcAshaccid ,       
   -- poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate,ISNULL(poshUserId,0)   
--RefNo-6-----------------------------------------------end-----------------------------------------------------------------  


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

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionWithMarginGSTSeparately')
   DROP view dbo.vwDailySalesCollectionWithMarginGSTSeparately
GO
 
--Modified on           : 04/09/2004                  
--Modified by           : Hariharan                   
--Comments              : Added LOsAccountsInvoiceHeader                  
--   : Added lnvoiceheader - Id grouping                  
--   : included service details of service boooking invoices                    
--   : Corrected join condition of ashops with LOsAccountsInvoiceHeader                  
--   : Corrected the service invoice query to consider the repinvdtype field                
---------------------------------------------------------------------------------------                        
--Modified on                  : 22/11/2010               
--Modified by                  : Nidheesh P V                
--Comments                     : AddedF&B               
---------------------------------------------------------------------------------------                        
--RefNo        : RefNo-2        
--Modified by  : Bijesh.B        
--Date         : 16/06/2011, 21/06/2011        
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)        
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-3        
--Modified by  : Nidheesh P V       
--Date         : 16/06/2011        
--Comments     : Used -costprice instead of costprice       
--Modified Area: Daily Sales Report      
----------------------------------------------------------------------------------------------            
--RefNo        : RefNo-4      
--Modified by  : Bijesh.B      
--Date         : 29/07/2011      
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong      
--             : since, Special invoice return after desp, reqqty is negative,      
--     -1 is multiplied with reqqty      
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-5        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 19/01/2012  
--Comments     : Modified F&B part.  
----------------------------------------------------------------------------------------------         
----------------------------------------------------------------------------------------------         
--Created by   : Bijesh.B   
--Date         : 29/03/2012  
--Ticket id    : JDJ-400367 (new report (rptdailysalescollectionGSTSeparately) for sonee - GST separation)  
--Comments     : Created new view and report (Copy of vwDailySalesCollectionWithMargin)  
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-6        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 26/06/2012  
--Comments     : Exchage rate multiplication problem in POS  
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B    
--Date         : 07/07/2012  
--Comments     : Corrected Margin value for credit invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-7 
--Date         : 09/07/2012  
--Comments     : Corrected Margin value for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-8 
--Date         : 09/07/2012  
--Comments     : Corrected gst amount for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-9
--Date         : 30/07/2012  
--Comments     : Included Other Charges Service Tax in Credit Invoice
----------------------------------------------------------------------------------------------       
   
CREATE VIEW [dbo].[vwDailySalesCollectionWithMarginGSTSeparately] AS                  
Select                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.poshbilldate, convert(numeric(18,8),sum(cashsales)) cashsales,                  
 convert(numeric(18,8),sum(dcashsales)) dcashsales,                   
 convert(numeric(18,8),sum(ccashsales)) ccashsales,                  
 convert(numeric(18,8),sum(creditsales)) creditsales,                  
 convert(numeric(18,8),sum(dcreditsales)) dcreditsales,                   
 convert(numeric(18,8),sum(ccreditsales)) ccreditsales,                   
 convert(numeric(18,8),sum(costvalue)) costvalue,                  
 convert(numeric(18,8),sum(dcostvalue)) dcostvalue,                   
 convert(numeric(18,8),sum(ccostvalue)) ccostvalue,                   
 convert(numeric(18,8),sum(margin)) margin,                  
 convert(numeric(18,8),sum(dmargin)) dmargin, 
 convert(numeric(18,8),sum(cmargin)) cmargin,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid        
 --RefNo-2 start -------------------------        
,convert(numeric(18,8),sum(PdChequeSales)) PdChequeSales,        
convert(numeric(18,8),sum(dPdChequeSales)) dPdChequeSales,        
convert(numeric(18,8),sum(cPdChequeSales)) cPdChequeSales,        
--RefNo-2 ends -------------------------        
convert(numeric(18,8),sum(GSTAmount))GSTAmount,  
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,  
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount  
from                   
 (                  
  select                   
   shopname, poshShopID, poshbilldate,   
   --convert(numeric(18,8),sum(posdunitprice )) cashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)) ccashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dcashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8),sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -  
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))))
	 - sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -  
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   departmentname, poshdepartmentid  departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d                   
  where                   
   poshBillid=posdBillid and poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=0 --RefNo-2  if No PD Cheque Amt involved                       
  group by                   
   shopname, departmentname, poshdepartmentid, poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,poshBillid                  
        
--RefNo-2 Start --------------------------------------------        
--CASH + PD CHEQUE -> Taking only cash amount        
union all        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   --convert(numeric(18,8), 
   --sum(posdunitprice )) cashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshdepexrate)) dcashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshexchangerate)) ccashsales,        
     
   --convert(numeric(18,8),sum(posdunitprice)-pdCheque.PosBankAmount) cashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) dcashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) ccashsales,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8), sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -   
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))))) -   
        sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshdepexrate)) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -   
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
            
   departmentname, poshdepartmentid  departmentid                  
   --,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dPdChequeSales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) cPdChequeSales  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved        
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                            
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
  
/*        
union all        
--CASH + PD CHEQUE -> Taking only Cheque amount        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,        
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales,      
   /*      
   sum(posdcostprice * posdquantity) costvalue,                   
         
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
        
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
        
   (convert(numeric(18,8), sum(posdunitprice ))) -                   
   sum(posdcostprice*posdquantity) margin,      
         
   (convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -   
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin,       
         
   (convert(numeric(18,8), sum(posdunitprice * poshexchangerate))) -       
   sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   */      
   0.0 costvalue,0.0 dcostvalue,0.0 ccostvalue,       
   0.0 margin,0.0 dmargin,0.0 cmargin,        
   departmentname, poshdepartmentid  departmentid,                  
    pdCheque.PosBankAmount as PdChequeSales,        
   (pdCheque.PosBankAmount * poshdepexrate) as  dPdChequeSales,        
   (pdCheque.PosBankAmount * poshexchangerate) as cPdChequeSales        
  from                
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved          
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                          
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
--RefNo-2 ends --------------------------------------------        
*/                  
 union all                  

--RefNo-9 start commented and added                    
  --select                   
  -- shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
  -- --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
  -- --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
  -- --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
  -- convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,             
  -- convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,             
  -- convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,             
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -       
  -- --sum(isnull(idcostprice*idquantity,0)))) margin,                   
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
  -- --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
  -- --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -             
		-- sum(isnull(idcostprice*idquantity,0)))) margin,             
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		-- (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		--   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
  -- departmentname, ihdepartmentid departmentid                   
  -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
  -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
  -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
  -- convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  --from                   
  -- losinvoiceheader  ih                  
  -- left outer join losinvoicedetail invd                  
  -- on ihInvoiceid=idInvoiceid and ihshopid=idshopid     
  -- left outer join                   
  -- (select                  
  --  ioShopID,ioInvoiceID,sum(ioAmount) ioAmount                  
  -- from                  
  --  losInvoiceOC                   
  -- group by                  
  -- ioShopID,ioInvoiceID) ocd                   
  -- on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
  -- ashops s, adepartmentmaster d                   
  --where                   
  -- IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
  -- ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  --group by                   
  -- shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
  -- ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
    
  
   --credit invoice
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) creditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihexchangerate) ccreditsales,             

   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -      
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,  
                    
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) -             
		 sum(isnull(idcostprice*idquantity,0)))) margin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihexchangerate -             
		   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from          
    
     losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid
   
   union all
   
   --Other Charges
   
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   
   convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) creditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate) ccreditsales,             

   0 costvalue,                   
   0 dcostvalue,                  
   0 ccostvalue,                  
                    
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))Margin,            
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))* ihdepexrate  dmargin,             
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))) * ihexchangerate cmargin,  
   
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihexchangerate)cGSTAmount  
  
  from          
     losinvoiceheader  ih                  
   --left outer join losinvoicedetail invd  on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join losInvoiceOC ocd  on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID         
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by  
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid,ocd.ioShopID,ocd.ioInvoiceID
--RefNo-9 ends

 union all                  
                  
  select                   
   shopname, ihShopID, ihinvoicedate,                  
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) Cashsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,         
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,                   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,             
   0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -                   
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -             
		sum(isnull(idcostprice*idquantity,0)))) margin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from                   
   losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join                   
   (select                  
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount        
   from                  
    losInvoiceOC                   
   group by                  
   ioShopID,ioInvoiceID) ocd                   
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
   ashops s, adepartmentmaster d                   
  where                   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=1 and ihdepartmentid = d.departmentid and ihtype ='i'                  
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
                  
 union all                  
   select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehexchangerate)) ccashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
   0.0 creditsales,0.0 dcreditsales , 0.0 ccreditsales , sum(sedcostprice * sedquantity) costvalue,                  
   sum(sedcostprice * sedquantity) * sehdepexrate dcostvalue,                   
   sum(sedcostprice * sedquantity) * sehexchangerate ccostvalue,                  
   --convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedquantity) margin,  
   --convert(numeric(18,8), sum(sedunitprice* sehdepexrate)) -                   
 --sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   --convert(numeric(18,8), sum(sedunitprice * sehexchangerate )) -   
   --sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) - sum(sedcostprice * sedquantity) margin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) -                   
          sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) -   
          sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
    departmentname, sehdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d            
  where          
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange = 'E' and sehshopid = shopid and sehdepartmentid = d.departmentid          
  group by      
   shopname, sehshopid, departmentname, sehdepartmentid, sehexchangedate ,                  
   departmentname,sehdepexrate, sehexchangerate,sehExchangeID                  
 union all                  
       
 -- RefNo-4 start  commented below      
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  sum(idunitprice )) cashsales, convert(numeric(18,8),                   
 ------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,8),                   
 ------  sum(idunitprice * ihexchangerate)) ccashsales,                  
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  (convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                   
 ------  (convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                   
 ------  (convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin, departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  ihdepartmentid =d.departmentid and idratetype=0 and ihproforma=0 and                   
 ------  ihshopid = shopid and ihcashinvoice=1 and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, departmentname, ihdepartmentid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
 ------ union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                   
 ------  0.0 ccashsales, convert(numeric(18,8), sum(idunitprice )) creditsales,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate)) dcreditsales,          
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate)) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                  
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                  
 ------  convert(numeric(18,8), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate) - sum(idcostprice*reqqty) * ihexchangerate) cmargin,                   
 ------  departmentname, ihDepartmentId departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  idratetype=0 and ihproforma=0 and ihshopid = shopid and                   
 ------  ihcashinvoice=0 and ihDepartmentId = d.departmentid                  
 ------  and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname, ihinvoicedate ,                   
 ------  ihexchangerate, ihdepexrate,ihInvoiceid                  
                  
 ------union all                  
 -- RefNo-4 ends      
                  
  select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),-sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehexchangerate)) ccashsales,                  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(-sedcostprice * sedExchangeQty) costvalue,    --RefNo-3              
   sum(-sedcostprice * sedExchangeQty) * sehdepexrate dcostvalue, sum(-sedcostprice * sedExchangeQty)     --RefNo-3             
   * sehexchangerate ccostvalue,  
    ---(convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedExchangeQty)) margin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -                   
   --    sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -   
    --    sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
           sum(sedcostprice * sedExchangeQty)) margin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -                   
        sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
        sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
  
   departmentname, sehdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d                   
  where        
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid                   
   and sehdepartmentid = d.departmentid                   
  group by                   
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,                  
   sehdepexrate,sedExchangeid                  

 union all       
       
 -- RefNo-4 start                  
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  -(sum(idunitprice ))) cashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihexchangerate))) ccashsales,                   
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(idcostprice * abs(reqqty)) costvalue,                   
 ------  sum(idcostprice * abs(reqqty)) * ihdepexrate dcostvalue, sum(idcostprice * abs(reqqty)) *                   
 ------  ihexchangerate ccostvalue,  -((convert(numeric(18,8), sum(idunitprice ))) -            
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0                    
 ------  and ihproforma=0 and ihshopid = shopid and ihTransfinished = 1                   
 ------  and ihcashinvoice=1 AND IDratetype=1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihdepartmentid, departmentname, ihshopid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
          
 ------union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice ))) creditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihdepexrate))) dcreditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihexchangerate))) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                   
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8),                   
 ------  sum(idunitprice ))) -  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND  
 ------  IHCANCELLED = 0 and ihproforma = 0 and ihshopid = shopid and                   
 ------  ihcashinvoice = 0 and idratetype = 1 and ihtransfinished = 1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname,                  
 ------  ihinvoicedate , ihexchangerate, ihdepexrate,ihInvoiceid                  
                  
 ------union all                  
      
-- special Invoice (cash)        
select         
shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccashsales,    
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales,   
  
0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty) margin,             
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,        
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty))* ihexchangerate cmargin,  
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d   
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                    
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all                                      
      
-------- special invoice - return before despatch                          
select shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,       
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-sum(idcostprice * reqqty) costvalue ,      
-sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
-sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
     
union all                                      
                                   
-- Special invoice return  - after desp                  
select shopname,                                     
 ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,     
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                        
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1         
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
-- special Invoice (credit)      
union all      
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccreditsales,    
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
       
 sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,      
--(convert(numeric(18,8), sum(idunitprice)))-sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))))-sum(idcostprice*reqqty) margin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice <>1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all         
      
-- special invoice - return before despatch                          
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,  
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,     
  
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
 -sum(idcostprice * reqqty) costvalue ,      
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) margin,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice <>1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                          
union all                                      
                                   
-- Special invoice return  - after desp                                    
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,  
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate))dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate))ccreditsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)dcreditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)ccreditsales,       
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
--idUnitPrice, idItemTaxAmount  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice <>1                                     
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
 -- RefNo-4 ends       
  union all                 
  select                   
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
   -- -convert(numeric(18,8), (sum(GRNDunitprice ))) creditsales,                   
   -- -convert(numeric(18,8), (sum(GRNDunitprice * grnhdepexRate))) dcreditsales,                   
   -- -convert(numeric(18,8), (sum(GRNDunitprice * grnhExchangeRate))) ccreditsales,   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) creditsales,                   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   
   -sum(grncostprice*grndquantity) costvalue, - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                  
   -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,                   
   -- -(convert(numeric(18,8), (sum(GRNDunitprice )))-sum(grncostprice*grndquantity)) margin,  
   -- -(convert(numeric(18,8), (sum(GRNDunitprice ))) -                   
   --    sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
   -- -(convert(numeric(18,8),(sum(GRNDunitprice ))) -  
   --     sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,                   
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))))-  
           sum(grncostprice*grndquantity)) margin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -                   
       sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -  
        sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,                   
   departmentname, grnhdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
    -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  from                   
   losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d                   
  where               
   GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0                   
   and grnhshopid = shopid and grnhdepartmentid = d.departmentid                   
  group by                   
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,                   
   grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID                  

  --hari added to include the service booking invoice parts replaced items                  
 UNION ALL                  
  
  --service invoice (cash)                
  select                   
   shopname, repinvdshopid, serinvhdate,  
   --convert(numeric(18,8),sum(repinvdrate* repinvdqty)) cashsales,  
   --convert(numeric(18,8),sum(repinvdrate* seinvhdepexrate * repinvdqty)) dcashsales,                  
   --convert(numeric(18,8),sum(repinvdrate* serinvhcmpexrate * repinvdqty)) ccashsales,                  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcashsales,            
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccashsales,            

   0.0 creditsales, 0.0 dcreditsales , 0.0 ccreditsales ,  sum(repinvdcostprice * repinvdqty) costvalue,                   
   sum(repinvdcostprice * repinvdqty) * seinvhdepexrate  dcostvalue,                   
   sum(repinvdcostprice * repinvdqty) *serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -  
   --  sum(repinvdcostprice * repinvdqty),                   
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,   
   --convert(numeric(18,8),(sum(repinvdrate  * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty)margin,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate dmargin,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
 -sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate cmargin,          
  
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --RefNo-8  start commneted, since this gst amount is taken care in below
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
 --convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
   ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
--RefNo-8 ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d                   
  where                   
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1                  
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, serinvhDepartmentid,                   
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid                   
                  
 union all                  
 
  --service Details  (cash)                
  select                   
   shopname, serinvhshopid, serinvhdate,  
   --convert(numeric(18,8) , serinvhserviceamt) cashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccashsales ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate)dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate)ccashsales ,             
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                       
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,    
   
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)),             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,       
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) *  serinvhcmpexrate) ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate)dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate)ccashsales ,             

   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount  
  from                   
--RefNo-8 start commented below
   --losserviceinvheader, ashops s, adepartmentmaster d                   
	 --where                   
	 --  serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1         
	 --  and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                  
   
 losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid   and Patindex('%y%',repinvdtype)>0 
 where                   
	serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1  
    and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends 
 union all
  
  --service invoice (credit)	    
    select                   
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , (sum(repinvdrate* repinvdqty))) creditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * seinvhdepexrate * repinvdqty))) dcreditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * serinvhcmpexrate * repinvdqty))) ccreditsales ,   
  
   convert(numeric(18,8),(sum( (repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
                     
   sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*                   
   seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty), convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty) * seinvhdepexrate , convert(numeric(18,8) ,                   
   --( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate ,                   
   
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * seinvhdepexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate,  
   
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  --RefNo-8  start commneted, since this gst amount is taken care in below
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
	 -- convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
	,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
  --RefNo-8  ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader,                   
   ashops s, adepartmentmaster d 
  where 
   serinvhid = repinvinvoiceid and                   
   serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is null                   
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid                    
   and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,                  
   serinvhcmpexrate ,serinvhid   
   
   union all
          
  --service Details   (credit)               
  select                   
 shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , serinvhserviceamt) creditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcreditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccreditsales ,     
   
   --RefNo-8 start commented below
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) creditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate) dcreditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate) ccreditsales ,             
   convert(numeric(18,8),serinvhserviceamt- (isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) creditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
   --RefNo-8 ends
   
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*seinvhdepexrate) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*serinvhcmpexrate) ,             
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount    
  from                   
  --RefNo-8 start commented below
  -- losserviceinvheader, ashops s, adepartmentmaster d                   
  --where                   
  -- serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                   
  losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0 
 where                   
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends
   
  union all                  


  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002                  
  --credit           
  select           
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,                   
   0.0 ccashsales,                  
    convert(numeric(18,8), sum(redunitprice)) creditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehdepexrate)  dcreditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehexchangerate) ccreditsales,
   sum(redcostprice * redquantity) costvalue,                   
   sum(redcostprice * redquantity) * rehdepexrate dcostvalue, 
   sum(redcostprice * redquantity) * rehexchangerate ccostvalue,
   (convert(numeric(18,8), sum(redunitprice ))) -  sum(redcostprice * redquantity) margin,
   (convert(numeric(18,8), sum(redunitprice * rehdepexrate))) -                   
		sum(redcostprice * redquantity) * rehdepexrate dmargin,
   (convert(numeric(18,8), sum(redunitprice * rehexchangerate))) - 
		sum(redcostprice * redquantity) * rehexchangerate cmargin,                   
   departmentname, rehdepartmentid                  
 ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,0,0,0  
  from                   
   losExportDetail, losExportHeader, ashops s, adepartmentmaster d                   
  where                   
   rehExportID = redExportID and rehshopid = redshopid AND                   
   reHCANCELLED=0 and rehtype ='i' and                  
   rehproforma=0 and rehshopid = shopid and rehcashinvoice=0 and                   
   rehdepartmentid = d.departmentid                   
  group by                   
   shopname, rehshopid, departmentname, rehdepartmentid, rehExportDate,                   
   rehdepexrate, rehexchangerate,rehExportID                   
            
 union all                  
 -- added From Vwcashsales -Margin Not calculating                  
                   
 select                   
  s.shopname, vws.sishopid, vws.siinvoicedate,                   
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,                   
  convert(numeric(18,8),sum(vws.sidamount)) as  dcashsales,  -- RefNo-7 corrected amount                  
  convert(numeric(18,8),sum(vws.sicamount)) as ccashsales,   -- RefNo-7 corrected amount                                  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
   0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
  convert(numeric(18,8),sum(vws.siamount))as margin,    -- RefNo-7 included  -vws.GSTAmount                              
  convert(numeric(18,8),sum(vws.sidamount))as  dmargin,    -- RefNo-7 included  -vws.GSTAmount                               
  convert(numeric(18,8),sum(vws.sicamount))as cmargin,  -- RefNo-7 included  -vws.GSTAmount                              
  d.departmentname,lah.aidepartmentid  departmentid                   
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
  , sum(vws.dGSTAmount)as dGSTAmount  
  , sum(vws.cGSTAmount)as cGSTAmount  
 from                   
  vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d ,ashops s                  
 where                   
  aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
  aishopid = sishopid and lah.aicashinvoice=1 and                   
  lah.aidepartmentid =d.departmentid and s.departmentid = d.departmentid                  
  and aiShopId = s.ShopId                  
 group by                   
  s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid, vws.siinvoicedate                  
  ,aidepexrate, aiexchangerate               
 union all                  
                  
    select s.shopname, vws.sishopid, vws.siinvoicedate,                   
    0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
    convert(numeric(18,8),sum(vws.siamount))as creditsales,                   
    convert(numeric(18,8),sum(vws.sidamount))as dcreditsales, -- RefNo-7 corrected amount                   
    convert(numeric(18,8),sum(vws.sidamount))as ccreditsales, -- RefNo-7 corrected amount                                    
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
    convert(numeric(18,8),sum(vws.siamount)) as margin,    -- RefNo-7 included  -vws.GSTAmount              
    convert(numeric(18,8),sum(vws.sidamount)) as dmargin,  -- RefNo-7 included  -vws.GSTAmount               
convert(numeric(18,8),sum(vws.sicamount)) as cmargin,  -- RefNo-7 included  -vws.GSTAmount   
    d.departmentname,lah.aidepartmentid  departmentid                   
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
    , sum(vws.dGSTAmount)as dGSTAmount  
    , sum(vws.cGSTAmount)as cGSTAmount  
    from vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d,ashops s      
    where aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
    aishopid = sishopid and lah.aicashinvoice=0 and lah.aidepartmentid =d.departmentid                  
    and s.departmentid = d.departmentid and s.ShopId = aiShopId group by                       
    s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid,vws.siinvoicedate,aiinvoiceid,
    aidepexrate                   
                   
    UniOn All -- added from vwCashSales                 
    --Shop debit credit notes and handling debit notes which are debit to the                
    -- customer and hence act as invoices to be settled                      
    Select  s.shopname,losdcnshopid,losdcndate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
    COnvert(numeric(18,8),Sum(losDCNAmount))  creditsales,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dcreditsales,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  ccreditsales,               
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    COnvert(numeric(18,8),Sum(losDCNAmount))  margin,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dmargin,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  cmargin,              
 d.departmentname,losdcndepartmentid                   
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2    
       ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount      
    From Ashops s,  losdebitcreditnote, adepartmentmaster d               
    Where  s.shopid = losdcnshopid And s.accountable Is Not Null                   
    And d.DepartmentID = losdcndepartmentid And losdcncancelled =0                    
    And losdcndebit =1  Group By s.shopname,d.departmentname,losdcnshopid,                  
    losdcndate, losdepexrate, losexchangerate,losdcndepartmentid              
              
    --hq serivce invoice dOne for shop                    
    Union all              
               
    Select  null, 0,ai.invoicedate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  creditsales,             
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dcreditsales,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  ccreditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)ccreditsales,         
  
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  margin,                     
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dmargin,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  cmargin,   
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)) * exchangerate)cmargin,        
                 
    d.departmentname,ai.departmentid           
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
     ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount   
     ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,  
      convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount  
  
  From accountsinvoiceheader ai, serviceinvoicedetails ser ,adepartmentmaster d              
    Where ai.invoiceid = ser.invoiceid And ai.companyid =                     
    ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0             
    and ai.departmentid = d.departmentid and ai.companyid = d.companyid               
    Group By  ai.invoicedate,depexrate,exchangerate,              
    d.departmentname,ai.departmentid              
        
  
 ----F&B---------------------------   
 --RefNo-5----------------------------------------------start----------------------------------------------------------------------------  
 ----------------------------------------  
 -- select v.* from        
 --(        
--select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales,       
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 --inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 --UNION ALL        
        
 --select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales,        
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,   
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 --inner join aitem a on a.itemid=fb_pd_dishid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 --where fb_pd_AddedItemtype=2        
 --)v       
  
/*  
union all  
  select shopname,poshShopID,poshBillDate,Cashsales,DepCashsales,ComCashsales,Creditsales,DepCreditsales,  
 ComCreditsales,costprice,dcostprice,ccostprice,margin,dmargin,cmargin,deptname,deptid,  
PdChequeSales,dPdChequeSales,cPdChequeSales  from  
 (        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid) costprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2        
  fb_pd_processdetailid  
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 UNION ALL        
        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2   
  fb_pd_processdetailid       
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 inner join aitem a on a.itemid=fb_pd_dishid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 where fb_pd_AddedItemtype=2        
  
  
 )  
  
  v        
 --RefNo-5----------------------------------------------end----------------------------------------------------------------------------  
  ----------------------------------------                  
  */  
     
 )cashcreditcollection      
group by                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid,                   
 cashcreditcollection.poshbilldate   
  
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID: Missing views found in SIMDI 07.08.12
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
GO
if exists( select * from sysobjects where id = object_id('dbo.vw_Report_Service_Bills'))
	begin
		drop view vw_Report_Service_Bills
	end
GO 
--sp_helptext vw_Report_Servic    -- Modified on  : 05/09/2003      
-- Modified by  : Kishore      
-- Comments     : Changed BillAmount to BillAmount + LcAmount in purchase bill      
----------------------------------------------------------------------------------------      
CREATE VIEW vw_Report_Service_Bills AS      
-- 1. Head quaters purchase bill      
select b.pbhCompanyID companyid, 0 as shopid, b.pbhDepartmentID departmentid,       
b.pbhBillID billsid, b.pbhVendorID,  b.pbhbillno billsno, b.pbhremarks,       
pbhvendorRefNo referenceno, b.pbhbilldate, b.pbhDueDateforPayment duedate,        
b.pbhBillAmount + b.pbhLcAmount pbhBillAmount, '0 - 30' as Due,       
'fpb' as type, b.updatetime       
from lospPurchaseBillHeader b       
where b.pbhCashPurchase =0 and b.pbhCancelled = 0 and       
(datediff(dd, b.pbhBillDate, getdate()) between 0 and 30)         
      
union all      
      
select b.pbhCompanyID companyid, 0 as shopid, b.pbhDepartmentID departmentid,       
b.pbhBillID billsid, b.pbhVendorID,  b.pbhbillno billsno, b.pbhremarks,       
pbhvendorRefNo referenceno, b.pbhbilldate, b.pbhDueDateforPayment duedate,        
b.pbhBillAmount + b.pbhLcAmount pbhBillAmount, '31 - 60' as Due,       
'fpb' as type, b.updatetime      
from lospPurchaseBillHeader b       
where b.pbhCashPurchase =0 and b.pbhCancelled = 0 and       
(datediff(dd, b.pbhBillDate, getdate()) between 31 and 60)         
      
union all      
      
select b.pbhCompanyID companyid, 0 as shopid, b.pbhDepartmentID departmentid,       
b.pbhBillID billsid, b.pbhVendorID,  b.pbhbillno billsno, b.pbhremarks,       
pbhvendorRefNo referenceno, b.pbhbilldate, b.pbhDueDateforPayment duedate,        
b.pbhBillAmount + b.pbhLcAmount pbhBillAmount, '61 - 90' as Due,       
'fpb' as type, b.updatetime      
from lospPurchaseBillHeader b       
where b.pbhCashPurchase =0 and b.pbhCancelled = 0 and       
(datediff(dd, b.pbhBillDate, getdate()) between 61 and 90)         
      
union all      
      
select b.pbhCompanyID companyid, 0 as shopid, b.pbhDepartmentID departmentid,       
b.pbhBillID billsid, b.pbhVendorID,  b.pbhbillno billsno, b.pbhremarks,       
pbhvendorRefNo referenceno, b.pbhbilldate, b.pbhDueDateforPayment duedate,        
b.pbhBillAmount + b.pbhLcAmount pbhBillAmount,' > 90' as Due,       
'fpb' as type, b.updatetime      
from lospPurchaseBillHeader b       
where b.pbhCashPurchase =0 and b.pbhCancelled = 0 and       
(datediff(dd, b.pbhBillDate, getdate()) > 90)        
      
-- 2. shop local purchase bill      
union all      
      
select ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,       
ph.lphbillno, ph.lphremarks, ph.lphVendorBillNo, ph.lphbilldate, lphDueDateforPayment,       
sum(lpdItemUnitPrice) billamount, '0 - 30' as Due, 'lpb' as type, ph.updatetime      
from loslocalpurchaseheader ph,  loslocalpurchasedetail pd      
where ph.lphbillid = pd.lpdbillid and ph.lphshopid = pd.lpdshopid and       
ph.lphcancelled = 0 and ph.lphcashpurchase = 0 and       
(datediff(dd, ph.lphBillDate, getdate()) between 0 and 30)        
group by ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,       
ph.lphbillno, ph.lphremarks, ph.lphVendorBillNo,      
ph.lphbilldate, lphDueDateforPayment, ph.updatetime      
      
union all      
      
select ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,       
ph.lphbillno, ph.lphremarks, ph.lphVendorBillNo, ph.lphbilldate, lphDueDateforPayment,       
sum(lpdItemUnitPrice) billamount, '31 - 60' as Due, 'lpb' as type, ph.updatetime      
from loslocalpurchaseheader ph,  loslocalpurchasedetail pd      
where ph.lphbillid = pd.lpdbillid and ph.lphshopid = pd.lpdshopid and       
ph.lphcancelled = 0 and ph.lphcashpurchase = 0 and       
(datediff(dd, ph.lphBillDate, getdate()) between 31 and 60)        
group by ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,       
ph.lphbillno, ph.lphremarks, ph.lphVendorBillNo,      
ph.lphbilldate, lphDueDateforPayment, ph.updatetime      
      
union all      
      
select ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,       
ph.lphbillno, ph.lphremarks, ph.lphVendorBillNo, ph.lphbilldate, lphDueDateforPayment,       
sum(lpdItemUnitPrice) billamount, '61 - 90' as Due, 'lpb' as type, ph.updatetime      
from loslocalpurchaseheader ph,  loslocalpurchasedetail pd      
where ph.lphbillid = pd.lpdbillid and ph.lphshopid = pd.lpdshopid and       
ph.lphcancelled = 0 and ph.lphcashpurchase = 0 and       
(datediff(dd, ph.lphBillDate, getdate()) between 61 and 90)        
group by ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,       
ph.lphbillno, ph.lphremarks, ph.lphVendorBillNo,      
ph.lphbilldate, lphDueDateforPayment, ph.updatetime      
      
union all      
      
select ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,       
ph.lphbillno, ph.lphremarks, ph.lphVendorBillNo, ph.lphbilldate, lphDueDateforPayment,       
sum(lpdItemUnitPrice) billamount,  ' > 90' as Due, 'lpb' as type, ph.updatetime      
from loslocalpurchaseheader ph,  loslocalpurchasedetail pd      
where ph.lphbillid = pd.lpdbillid and ph.lphshopid = pd.lpdshopid and       
ph.lphcancelled = 0 and ph.lphcashpurchase = 0 and       
(datediff(dd, ph.lphBillDate, getdate())  > 90)        
group by ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,       
ph.lphbillno, ph.lphremarks, ph.lphVendorBillNo,      
ph.lphbilldate, lphDueDateforPayment, ph.updatetime      
      
union all      
      
-- 3.accounts bill      
select  b.CompanyID, 0 as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno,       
b.remarks, b.ReferenceNo, b.billdate, dateadd(dd,b.dueperiod,b.billdate), sum(bd.amount)       
billamount,  '0 - 30' as Due , 'accb' as type, b.updatetime      
from billsdebitdetails bd, bills b      
where b.companyid = bd.companyid and b.billsid = bd.billsid and       
b.cancelled = 0 and b.cashpurchase = 0 and (datediff(dd, b.BillDate, getdate())  between 0 and 30)        
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,       
b.remarks, b.ReferenceNo, b.billdate, b.updatetime, b.dueperiod, b.DepartmentID      
      
union all      
      
select  b.CompanyID, 0 as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno,       
b.remarks, b.ReferenceNo, b.billdate, dateadd(dd,b.dueperiod,b.billdate), sum(bd.amount)       
billamount, '31 - 60' as Due , 'accb' as type, b.updatetime      
from billsdebitdetails bd, bills b      
where b.companyid = bd.companyid and b.billsid = bd.billsid and       
b.cancelled = 0 and b.cashpurchase = 0 and (datediff(dd, b.BillDate, getdate())  between 31 and 60)        
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,       
b.remarks, b.ReferenceNo, b.billdate, b.updatetime, b.dueperiod, b.DepartmentID      
      
union all      
      
select  b.CompanyID, 0 as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno,       
b.remarks, b.ReferenceNo, b.billdate, dateadd(dd,b.dueperiod,b.billdate), sum(bd.amount)       
billamount, '61 - 90' as Due , 'accb' as type, b.updatetime      
from billsdebitdetails bd, bills b      
where b.companyid = bd.companyid and b.billsid = bd.billsid and       
b.cancelled = 0 and b.cashpurchase = 0 and (datediff(dd, b.BillDate, getdate())  between 61 and 90)        
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,       
b.remarks, b.ReferenceNo, b.billdate, b.updatetime, b.dueperiod, b.DepartmentID      
      
union all      
      
select  b.CompanyID, 0 as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno,       
b.remarks, b.ReferenceNo, b.billdate, dateadd(dd,b.dueperiod,b.billdate), sum(bd.Amount)       
billamount, ' > 90' as Due , 'accb' as type, b.updatetime      
from billsdebitdetails bd, bills b      
where b.companyid = bd.companyid and b.billsid = bd.billsid and       
b.cancelled = 0 and b.cashpurchase = 0 and (datediff(dd, b.BillDate, getdate())  > 90)        
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,       
b.remarks, b.ReferenceNo, b.billdate, b.updatetime, b.dueperiod, b.DepartmentID      
      
union all      
      
-- 4.credit note      
SELECT dcn.DCNCompanyid, 0 as shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNvendorID,       
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno, dcn.DCNDate, dcn.dcndate,       
DCNAmount,  '0 - 30'  as Due, 'cn' as type, dcn.updatetime      
FROM debitcreditnote dcn      
WHERE dcn.DCNvendorID is not null and dcn.DCNDebit =0 and dcn.DCNCancelled= 0      
and (datediff(dd,  dcn.dcnDate, getdate())  between 0 and 30)      
      
union all      
      
SELECT dcn.DCNCompanyid, 0 as shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNvendorID,       
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno, dcn.DCNDate, dcn.dcndate,       
DCNAmount, '31 - 60'  as Due, 'cn' as type, dcn.updatetime      
FROM debitcreditnote dcn      
WHERE dcn.DCNvendorID is not null and dcn.DCNDebit =0 and dcn.DCNCancelled= 0      
and (datediff(dd,  dcn.dcnDate, getdate())  between 31 and 60)      
      
union all      
      
SELECT dcn.DCNCompanyid, 0 as shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNvendorID,       
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno, dcn.DCNDate, dcn.dcndate,       
DCNAmount, '61 - 90'  as Due, 'cn' as type, dcn.updatetime      
FROM debitcreditnote dcn      
WHERE dcn.DCNvendorID is not null and dcn.DCNDebit =0 and dcn.DCNCancelled= 0      
and (datediff(dd,  dcn.dcnDate, getdate())  between 61 and 90)      
      
union all      
      
SELECT dcn.DCNCompanyid, 0 as shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNvendorID,       
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno, dcn.DCNDate, dcn.dcndate,       
DCNAmount, ' > 90'  as Due, 'cn' as type, dcn.updatetime      
FROM debitcreditnote dcn      
WHERE dcn.DCNvendorID is not null and dcn.DCNDebit =0 and dcn.DCNCancelled= 0      
and (datediff(dd,  dcn.dcnDate, getdate())  > 90)      
      
union all      
      
SELECT dcn.losDCNCompanyid, losdcnshopid shopid, dcn.losdcndepartmentid, dcn.losDCNId,       
dcn.losDCNvendorID, dcn.losdcnno, dcn.losdcnremarks, dcn.losreferenceno, dcn.losDCNDate,       
dcn.losdcndate, losDCNAmount, '0 - 30'  as Due,       
'scn' as type, dcn.updatetime FROM losdebitcreditnote dcn      
WHERE dcn.losDCNvendorID is not null and dcn.losDCNDebit =0 and dcn.losDCNCancelled= 0      
and (datediff(dd, dcn.losdcnDate,getdate() ) between 0 and 30)      
      
union all      
      
SELECT dcn.losDCNCompanyid, losdcnshopid shopid, dcn.losdcndepartmentid, dcn.losDCNId,       
dcn.losDCNvendorID, dcn.losdcnno, dcn.losdcnremarks, dcn.losreferenceno, dcn.losDCNDate,       
dcn.losdcndate, losDCNAmount, '31 - 60'  as Due,       
'scn' as type, dcn.updatetime FROM losdebitcreditnote dcn      
WHERE dcn.losDCNvendorID is not null and dcn.losDCNDebit =0 and dcn.losDCNCancelled= 0      
and (datediff(dd, dcn.losdcnDate,getdate() ) between 31 and 60)      
      
union all      
      
SELECT dcn.losDCNCompanyid, losdcnshopid shopid, dcn.losdcndepartmentid, dcn.losDCNId,       
dcn.losDCNvendorID, dcn.losdcnno, dcn.losdcnremarks, dcn.losreferenceno, dcn.losDCNDate,       
dcn.losdcndate, losDCNAmount, '61 - 90'  as Due,       
'scn' as type, dcn.updatetime FROM losdebitcreditnote dcn      
WHERE dcn.losDCNvendorID is not null and dcn.losDCNDebit =0 and dcn.losDCNCancelled= 0      
and (datediff(dd, dcn.losdcnDate,getdate() ) between 61 and 90)      
      
union all      
      
SELECT dcn.losDCNCompanyid, losdcnshopid shopid, dcn.losdcndepartmentid, dcn.losDCNId,       
dcn.losDCNvendorID, dcn.losdcnno, dcn.losdcnremarks, dcn.losreferenceno, dcn.losDCNDate,       
dcn.losdcndate, losDCNAmount, ' > 90'  as Due,       
'scn' as type, dcn.updatetime FROM losdebitcreditnote dcn      
WHERE dcn.losDCNvendorID is not null and dcn.losDCNDebit =0 and dcn.losDCNCancelled= 0      
and (datediff(dd, dcn.losdcnDate,getdate() ) > 90)      
      
union all      
      
-- receipt from suppliers considered as bills      
select rh.companyid, 0 shopid, rh.departmentid, rh.receiptid, rh.vendorid, rh.receiptno,       
rh.remarks,cbreferenceno, rh.receiptdate, rh.receiptdate  , rh.customeramount,  '0 - 30' due,        
'rf' type, rh.updatetime      
from receiptvoucherheader rh where rh.cancelled =0 and vendorid is not null      
and (datediff(dd, rh.receiptdate,getdate()) between 0 and 30)      
      
union all      
      
select rh.companyid, 0 shopid, rh.departmentid, rh.receiptid, rh.vendorid,       
rh.receiptno, rh.remarks,cbreferenceno, rh.receiptdate, rh.receiptdate ,       
rh.customeramount, '31 - 60' due,  'rf' type, rh.updatetime      
from receiptvoucherheader rh where rh.cancelled =0 and vendorid is not null      
and (datediff(dd, rh.receiptdate,getdate()) between 31 and 60)      
      
union all      
      
select rh.companyid, 0 shopid, rh.departmentid, rh.receiptid, rh.vendorid,       
rh.receiptno, rh.remarks,cbreferenceno, rh.receiptdate, rh.receiptdate ,       
rh.customeramount,  '61 - 90' due,  'rf' type, rh.updatetime      
from receiptvoucherheader rh where rh.cancelled =0 and vendorid is not null      
and (datediff(dd, rh.receiptdate,getdate()) between 61 and 90)      
      
union all      
      
select rh.companyid, 0 shopid, rh.departmentid, rh.receiptid, rh.vendorid,       
rh.receiptno, rh.remarks,cbreferenceno, rh.receiptdate, rh.receiptdate ,       
rh.customeramount,  ' > 90' due,  'rf' type, rh.updatetime      
from receiptvoucherheader rh where rh.cancelled =0 and vendorid is not null      
and (datediff(dd, rh.receiptdate,getdate()) > 90)
GO     
      
--************************************************************************
--************************************************************************
if exists( select * from sysobjects where id = object_id('dbo.vw_Report_service_CustomerLedger'))
	begin
		drop view vw_Report_service_CustomerLedger
	end
GO
--sp_helptext vw_Report_service_CustomerLedger  
  
/****** Object:  View dbo.vwCustomerLedger    Script Date: 17/10/2005 10:38:34 AM ******/        
-- Modified by   : SDL on 19/Sep/2005, Shop Credit note corrected        
-- Modified on   : 04/08/2003,25/08/2003        
-- Modified by  : R Harikrishnan        
-- Comments  : Corrected the depexchange rate multiplication pblm,        
--   : added exchange rates.         
--   : Added ((rh.amount - (creditamount * isnull(cusvenaccexrate, 0)))        
--   : instead of rhamount        
-----------------------------------------------------------------------------------------------        
-- Comments  : V3        
--   : added reexport related selection        
--   : included the accountable option of shop        
--   : added MultiCustomer        
--   : added customer category and group by venki on 070603        
-----------------------------------------------------------------------------------------------        
-- Modified on          : 26/11/2003, 10/01/2004, 23/01/2004, 06/02/2004, 14/02/2004, 06/04/2004        
-- Modified by          : Kishore, Hariharan R, Hariharan R, Hariharan R, Hariharan R, Hariharan R        
-- Comments             : Added SettledAmt column, added ihTransFinished = 1 condition        
--   : included queries for manam bills        
--   : Considered the cash paid by option in losAccountsinvoiceheader selection        
--   : Corrected the losAccountsInvoiceheader, resp amount is taken considering        
--   : the cash paid by shop option        
--   : settled amt selected for manam bills to show partsetted correctly in reports        
-----------------------------------------------------------------------------------------------        
CREATE VIEW vw_Report_service_CustomerLedger AS        
--1 hq service invoice        
select         
 ah.companyid, ah.departmentid, ah.customerid, ah.invoicedate tdate,         
 isnull(vw.refno,'') as secref,  ah.invoiceno tno, isnull(ah.orderno,'') cr,         
 'Service Invoice' as type, ah.remarks, Case When (SD.InvoiceID is not null) Then         
 isnull(sum(ServiceQty * Amount),0)-isnull(Discount,0) End as invamt, 0.0 as pmtamt,        
 dateadd(dd, ah.dueperiod,ah.invoicedate) duedate, datediff(dd,ah.invoicedate,getdate()) age,        
 ah.updatetime, vw.setdate,         
 convert(numeric(18,2), (isnull(sum(ServiceQty * Amount),0)-isnull(Discount,0))  *         
 exchangerate) cinvamt, 0.0 cpmtamt, ah.financialid, '' chequedetails, c.debtoraccid,         
 convert(numeric(18,2), (isnull(sum(ServiceQty * Amount),0)-isnull(Discount,0))  * depexrate) dinvamt, 0.0 dpmtamt,        
 c.customercategory, isnull(c.custgroupname,'') custgroupname, ah.exchangerates,         
        sum(isnull(vw.settledamt, 0)) SettledAmt,'' shopid  ,c.cusGroupID      
from         
 acustomermaster c, accountsinvoiceheader ah         
 Left outer join ServiceInvoiceDetails SD on AH.InvoiceID = SD.InvoiceID and         
 AH.CompanyID = SD.CompanyID         
 left outer join vwaccinvoicesettlementno vw on ah.companyid = vw.companyid and         
 ah.invoiceid = vw.accinvoiceid        
where         
 c.customerid = ah.customerid and ah.cancelled =0 and ah.proforma =0 and         
 ah.cashinvoice = 0        
GROUP BY        
 ah.invoicedate,ah.CompanyID, ah.departmentid, ah.customerid, debtoraccid, vw.refno, ah.invoiceno,ah.orderno,        
 sd.invoiceid, ah.remarks, ah.dueperiod, ah.updatetime, vw.setdate, ah.exchangerate, ah.depexrate,         
 ah.financialid, discount,c.customercategory,c.custgroupname,ah.exchangerates,c.cusGroupID       
        
union all         
--2 shop acc invoices        
select         
 ah.aicompanyid, ah.aidepartmentid, ah.aicustomerid, ah.aiinvoicedate tdate,         
 isnull(vw.refno,'') as secref,  ah.aiinvoiceno tno, isnull(ah.aiorderno,'') cr,         
 'Service Invoice' as type, ah.airemarks, convert(numeric(18,2), (        
 Case convert(int, isnull(aiCashPaidByShop,0)) when 0 then sum(siServiceQty * siAmount)          
 else sum((siServiceQty * siAmount) + siClearingCommAmt) end )) as invamt, 0.0 as pmtamt,         
 dateadd(dd, aidueperiod,ah.aiinvoicedate) duedate, datediff(dd,ah.aiinvoicedate,getdate()) age,      
 ah.updatetime, vw.setdate, convert(numeric(18,2), (        
 Case convert(int, isnull(aiCashPaidByShop,0)) when 0 then sum(siServiceQty * siAmount) *         
 ah.aiexchangerate else sum((siServiceQty * siAmount) + siClearingCommAmt) *         
 ah.aiexchangerate end )), 0.0 cpmtamt, ah.aifinancialid, '' chequedetails,         
 c.debtoraccid,          
 convert(numeric(18,2), (        
 Case convert(int, isnull(aiCashPaidByShop,0)) when 0 then sum(siServiceQty * siAmount) *         
 ah.aidepexrate else sum((siServiceQty * siAmount) + siClearingCommAmt) *         
 ah.aidepexrate end )), 0.0 dpmtamt,        
 c.customercategory,isnull(c.custgroupname,'')custgroupname,        
        ah.aidexchangerates, sum(isnull(vw.settledamt, 0)) settledamt,ah.aishopid ,c.cusGroupID       
from         
 acustomermaster c, ashops s, losaccountsinvoiceheader ah         
 Left outer join losServiceInvoiceDetails SD on AH.aiInvoiceID = SD.siInvoiceID and         
 AH.aiCompanyID = SD.siCompanyID and ah.aishopid = sd.sishopid         
 left outer join vwshopaccinvoicesettlementno vw on ah.aicompanyid = vw.companyid and         
 ah.aiinvoiceid = vw.accinvoiceid and ah.aishopid = vw.shopid        
where         
 ah.aishopid =s.shopid and c.customerid = ah.aicustomerid and ah.aicancelled =0  and ah.aiproforma = 0 and         
 ah.aicashinvoice = 0 and s.accountable is not null        
GROUP BY         
 ah.aiinvoicedate,ah.aiCompanyID, ah.aidepartmentid, ah.aicustomerid, debtoraccid,         
 vw.refno, ah.aiinvoiceno,ah.aiorderno,sd.siinvoiceid, ah.airemarks, ah.aidueperiod,         
 ah.updatetime,  vw.setdate, ah.aiexchangerate,ah.aidepexrate, ah.aifinancialid,         
 c.customercategory,c.custgroupname,ah.aidexchangerates,         
 convert(int, isnull(aiCashPaidByShop,0)),ah.aishopid ,c.cusGroupID    
        
union all          
        
-- 3 shop credit invoices        
select         
 ih.companyid, ih.ihdepartmentid, ih.customerid, ih.invoicedate tdate, isnull(vw.refno,'') as secref,          
 ih.invoiceno tno, isnull(ih.referenceno,'') cr, 'Sales Invoice' as type, ih.remarks, amount  invamt, 0.0  pmtamt,         
 ih.ihduedate, datediff(dd,ih.invoicedate,getdate()) age, ih.updatetime, vw.setdate,         
 convert(numeric(18,2),(amount * ihexchangerate)) cinvamt, 0.0 cpmtamt, ih.ihfinancialid,         
 '' chequedetails, c.debtoraccid, convert(numeric(18,2),(amount * ihdepexrate)) dinvamt,         
 0.0 dpmtamt, c.customercategory,isnull(c.custgroupname,'')custgroupname,        
        ih.ihexchangerates, isnull(vw.settledamt, 0) settledamt,ih.shopid,c.cusGroupID       
from         
 ashops s, acustomermaster c, vwshopCreditInvoice ih         
 left outer join vwshopinvoicesettlementno vw on ih.companyid = vw.companyid and         
 ih.invoiceid = vw.invoiceid and ih.shopid = vw.shopid         
where         
 s.shopid = ih.shopid and c.customerid = ih.customerid         
 and s.accountable is not null        
        
union all        
        
--4 shop special invoice        
select         
 ih.companyid, ih.ihdepartmentid, ih.customerid, ih.invoicedate tdate, isnull(vw.refno,'') as secref,          
 ih.invoiceno tno, isnull(ih.referenceno,'') cr, 'Sales Invoice' as type, ih.remarks,         
 amount as invamt, 0.0 as pmtamt, ih.ihduedate, datediff(dd,ih.invoicedate,getdate()) age,         
 ih.updatetime, vw.setdate, convert(numeric(18,2),(amount * ih.ihexchangerate)) cinvamt,         
 0.0 cpmtamt, ih.ihfinancialid, '' chequedetails, c.debtoraccid, convert(numeric(18,2),(amount *         
 ih.ihdepexrate)) dinvamt, 0.0 dpmtamt, c.customercategory,isnull(c.custgroupname,'')custgroupname,        
 ih.ihexchangerates, isnull(vw.settledamt, 0) settledamt,ih.shopid ,c.cusGroupID        
from         
 ashops s, acustomermaster c, vwspecialinvoiceamount ih         
 left outer join vwshopsplinvoicesettlementno vw on ih.companyid = vw.companyid and         
 ih.invoiceid = vw.invoiceid and ih.shopid = vw.shopid         
where         
 s.shopid = ih.shopid and ih.customerid = c.customerid and s.accountable is not null        
        
union all        
        
--5 hq receipt        
select         
 rh.companyid, rh.departmentid, rh.customerid, rh.receiptdate tdate,'' as secref,         
 rh.receiptno tno, '' cr, 'Receipt' type, rh.remarks, 0.0  invamt, rh.customeramount pmtamt,         
 null duedate, 0 age, rh.updatetime, null, 0.0 cinvamt, isnull(convert(numeric(18,4),         
 ((rh.amount -(isnull(rh.creditamount,0)* isnull(rh.cusvenaccexrate,0))) * rh.exchangerate)),0)  cpmtamt, financialid, chequedetails, c.debtoraccid, 0.0 dinvamt,         
 isnull(convert(numeric(18,4), ((rh.amount -(isnull(rh.creditamount,1)* isnull(rh.cusvenaccexrate,0))) * depexrate)),0)          
 dpmtamt,c.customercategory,isnull(c.custgroupname,'')custgroupname, rh.exchangerates,         
 0 settledamt,'',c.cusGroupID       
from         
 acustomermaster c, receiptvoucherheader rh         
where         
 c.customerid = rh.customerid and rh.cancelled = 0 and rh.customerid is not null        
        
union all        
        
-- 6 hq payment        
select         
 ph.phcompanyid, ph.phdepartmentid, ph.phcustomerid, ph.phpaymentdate tdate, '' as secref,         
 ph.phpaymentno tno, '' cr, 'Payment' type, ph.phremarks, ph.phcustomeramount invamt, 0.0 pmtamt,         
 null duedate, 0 age, ph.updatetime, null, isnull(convert(numeric(18,4),         
 ((ph.phAmount -(isnull(ph.phdebitamount,0)* isnull(ph.vencusaccexrate,0))) * ph.phexchangerate)),0)        
 cinvamt, 0.0 cpmtamt, phfinancialid, '' ChequeDetails, c.debtoraccid,         
 isnull(convert(numeric(18,4), ((ph.phamount -(isnull(ph.phdebitamount,0)* isnull(ph.vencusaccexrate,0)))        
 * ph.phdepexrate)),0) dinvamt, 0.0 dpmtamt,c.customercategory,        
 isnull(c.custgroupname,'')custgroupname,ph.phexchangerates, 0 settledamt,'',c.cusGroupID       
from         
 acustomermaster c, ahqpaymentvoucherheader ph where ph.phcancelled =0 and         
 phcustomerid is not null and ph.phcustomerid = c.customerid        
        
union all        
-- 7 hq debit note        
select         
 dcn.dcncompanyid, dcn.dcndepartmentid, dcn.dcncustomerid, dcn.dcndate tdate,         
 isnull(vw.refno,'') as secref, dcn.dcnno tno, '' cr,         
        'Debit Note' type, dcn.dcndetails remarks,         
 dcn.dcnamount invamt, 0.0 pmtamt, 0 duedate,         
        datediff(dd,dcn.dcndate, getdate()) age,         
 dcn.updatetime, vw.setdate,         
        convert(numeric(18,2),(dcn.dcnamount * dcnexchangerate)) cinvamt,         
 0.0 cpmtamt,  dcnfinancialid, '' ChequeDetails, c.debtoraccid,         
 convert(numeric(18,2),(dcn.dcnamount * dcndepexrate)) dinvamt, 0.0 dpmtamt,        
 c.customercategory,isnull(c.custgroupname,'')custgroupname,         
        dcn.dcnexchangerates, isnull(vw.settledamt, 0) settledamt,'',c.cusGroupID        
from         
 acustomermaster c, debitcreditnote dcn left outer join vwdebitnotesettlementno vw         
        on dcn.dcncompanyid = vw.companyid         
        and dcn.dcnid = vw.dcnid         
where         
 c.customerid = dcn.dcncustomerid         
        and dcn.dcncancelled = 0         
        and dcn.dcncustomerid is not null         
        and dcn.dcndebit = 1        
        
union all        
        
-- 8 hq credit note        
select         
 dcn.dcncompanyid, dcn.dcndepartmentid, dcn.dcncustomerid, dcn.dcndate tdate, '' as secref, dcn.dcnno tno,        
 '' cr, 'Credit Note' type, dcn.dcndetails remarks, 0.0 invamt, dcn.dcnamount pmtamt, null duedate,         
 0 age, dcn.updatetime,  null, 0.0 cinvamt, convert(numeric(18,2),(dcn.dcnamount * dcnexchangerate)) cpmtamt,         
 dcnfinancialid, '' ChequeDetails, c.debtoraccid, 0.0 dinvamt,         
 convert(numeric(18,2),dcn.dcnamount * dcndepexrate) dpmtamt, c.customercategory,        
 isnull(c.custgroupname,'')custgroupname,dcn.dcnexchangerates, 0 settledamt,''  ,c.cusGroupID      
from         
 acustomermaster c, debitcreditnote dcn         
where         
 c.customerid = dcn.dcncustomerid and dcn.dcncancelled =0 and         
 dcn.dcncustomerid is not null and dcn.dcndebit =0         
        
union all        
        
-- 9 shop debit note        
select         
 losdcncompanyid, losdcndepartmentid, losdcncustomerid, losdcndate tdate, '' as secref,         
 losdcnno tno, '' cr, 'Shop Debit Note' type, losdcnremarks remarks, losdcnamount invamt,         
 0.0 pmtamt, losdcndate duedate, datediff(dd,losdcndate,getdate()) age, updatetime, null setdate,         
 convert(numeric(18,2),(losdcnamount * losexchangerate)) cinvamt, 0.0 cpmtamt,         
 losfinancialid, '' ChequeDetails, c.debtoraccid, convert(numeric(18,2),(losdcnamount *         
 losdepexrate)) dinvamt, 0.0 dpmtamt, c.customercategory,        
 isnull(c.custgroupname,'')custgroupname,losdexchangerates, 0 settledamt,s.shopid ,c.cusGroupID       
from         
 ashops s, acustomermaster c, losdebitcreditnote         
where         
 s.shopid = losdcnshopid and  c.customerid = losdcncustomerid and losdcncancelled =0 and         
 losdcncustomerid is not null and losdcndebit =1 and s.accountable is not null        
        
union all        
        
-- 10 shop credit note        
-- SDL MODIFIED ON Company Inv and Payment amount were Corrected as it was Swapped between        
select         
 losdcncompanyid, losdcndepartmentid, losdcncustomerid, losdcndate tdate, '' as secref,         
 losdcnno tno, '' cr, 'Shop Credit Note' type, losdcnremarks remarks, 0.0 invamt,         
 losdcnamount  pmtamt, losdcndate duedate, datediff(dd,losdcndate,getdate()) age,         
 updatetime, null setdate,0.0         
 cinvamt,  convert(numeric(18,2),(losdcnamount * losexchangerate)) cpmtamt, losfinancialid, '' ChequeDetails, c.debtoraccid,         
 0.0 dinvamt, convert(numeric(18,2),(losdcnamount *  losdepexrate))  dpmtamt,        
 c.customercategory,isnull(c.custgroupname,'')custgroupname,        
        losdexchangerates, 0 settledamt,s.shopid  ,c.cusGroupID      
from         
 ashops s, acustomermaster c, losdebitcreditnote         
where         
 s.shopid = losdcnshopid and c.customerid = losdcncustomerid and         
 losdcncancelled =0 and losdcncustomerid is not null         
 and losdcndebit =0 and s.accountable is not null        
        
union all        
        
-- 11 GOODS RETURN INCLUDED        
select         
 h.grncompanyid, ih.ihdepartmentid, h.GrnhCustomerID, h.GrnhGoodsreturnnoteDate tdate,         
 '' as secref, h.GrnhGoodsreturnnoteNO tno, '' cr, 'Return' type, '' remarks,         
 0.0  invamt, grnamt pmtamt, null duedate, 0 age, h.updatetime, null, 0.0 cinvamt,         
 convert(numeric(18,2),(grnamt * grnhexchangerate)) cpmtamt, grnhfinancialid,         
 '' ChequeDetails, c.debtoraccid, 0.0 dinvamt, convert(numeric(18,2),(grnamt *         
 grnhdepexrate)) dpmtamt ,c.customercategory,isnull(c.custgroupname,'')custgroupname,        
 h.grnexchangerates, 0 settledamt,h.grnhshopid ,c.cusGroupID       
from         
 ashops s, acustomermaster c, losgoodsreturnnoteheader h, vwposgrnamount d,         
 losinvoiceheader ih         
where         
 h.grnhshopid = s.shopid and c.customerid = grnhcustomerid and         
 h.grnhgoodsreturnnoteid= d.grnhgoodsreturnnoteid  and h.grnhshopid = d.grnhshopid and         
 h.grncompanyid  = d.grncompanyid and ih.ihinvoiceid=h.GrnhInvoiceID and         
 ih.ihcompanyid = h.grncompanyid and ih.ihshopid=h.grnhshopid and h.GrnhCancel = 0 and         
 h.grnhcustomerid is not null and s.accountable is not null        
        
union all        
        
-- 12 specialinvoice return        
select         
 h.ihcompanyid, h.ihdepartmentid, h.ihCustomerID , h.ihinvoicedate tdate,         
 isnull(ih.ihinvoiceno,'') as secref, h.ihinvoiceno tno, '' cr, 'Special Return' type,         
 '' remarks, 0.0  invamt, returnamount pmtamt, null duedate, 0 age, h.updatetime, null,         
 0.0 cinvamt, convert(numeric(18,2),returnamount * h.ihexchangerate) cpmtamt,         
 ih.IhFinancialID, '' ChequeDetails, c.debtoraccid, 0.0 dinvamt,         
 convert(numeric(18,2),returnamount * h.ihdepexrate) dpmtamt, c.customercategory,        
 isnull(c.custgroupname,'')custgroupname,h.ihexchangerates, 0 settledamt,s.shopid ,c.cusGroupID       
from         
 ashops s, acustomermaster c, losspecialinvoiceheader h,         
 vwspecialreturninvoicetosettle d, losspecialinvoiceheader ih         
where         
 s.shopid = h.ihshopid and c.customerid = h.ihcustomerid and h.ihcashinvoice =0 and         
 h.ihinvoiceid= d.ihinvoiceid and h.ihshopid =          
 d.ihshopid and h.ihcompanyid  = d.ihcompanyid and ih.ihinvoiceid = d.returnedinvid and         
 ih.ihcompanyid = h.ihcompanyid and ih.ihshopid=h.ihshopid and         
 h.ihcancelled = 0 and h.ihcustomerid is not null and s.accountable is not null        
 and h.ihTransfinished = 1        
union all        
        
-- 13 shop booking service invoices        
select         
 ih.companyid, ih.serinvhdepartmentid, ih.customerid, ih.invoicedate tdate,         
 isnull(vw.refno,'') as secref, ih.invoiceno tno, isnull(ih.referenceno,'') cr,        
 'Booking Invoice' as type, ih.remarks, serinvhamount  invamt, 0.0  pmtamt,         
 ih.serinvhduedate, datediff(dd,ih.invoicedate,getdate()) age, ih.serinvhupdatetime,         
 vw.setdate, convert(numeric(18,2),(serinvhamount * serinvhcmpexrate)) cinvamt,         
 0.0 cpmtamt, serinvfinancialid, '' ChequeDetails, c.debtoraccid,         
 convert(numeric(18,2),(serinvhamount * seinvhdepexrate)) dinvamt, 0.0 dpmtamt,        
 c.customercategory,isnull(c.custgroupname, '') custgroupname,        
        ih.serinvhexchangerates, isnull(vw.settledamt, 0) settledamt,s.shopid ,c.cusGroupID        
from         
 ashops s, acustomermaster c, vwbookingservinvoices ih         
 left outer join vwbookservicesettlementno vw on ih.companyid = vw.companyid and         
 ih.invoiceid = vw.invoiceid and ih.shopid = vw.shopid         
where         
 s.shopid = ih.shopid and c.customerid = ih.customerid and s.accountable is not null        
        
union all        
        
--REEXPORT DETAIL OF CUSTOMER        
select         
 ih.companyid, ih.rehdepartmentid, ih.customerid, ih.invoicedate tdate,         
 isnull(vw.refno,'') as secref,  ih.invoiceno tno, isnull(ih.referenceno,'') cr,         
 'Re-Export' as type, ih.remarks, rehexportamount  invamt, 0.0  pmtamt, ih.rehduedate,         
 datediff(dd,ih.invoicedate,getdate()) age, ih.rehupdatetime, vw.receiptdate,         
 convert(numeric(18,2),(rehexportamount * rehexchangerate)) cinvamt,        
 0.0 cpmtamt, ih.rehfinancialid, '' chequedetails, c.debtoraccid,         
 convert(numeric(18,2),(rehexportamount * rehdepexrate)) dinvamt,         
 0.0 dpmtamt , c.customercategory,isnull(c.custgroupname,'')custgroupname,        
 ih.rehexchangerates, isnull(vw.settledamt, 0) settledamt,s.shopid ,c.cusGroupID        
from         
 ashops s, acustomermaster c, vwreexportinvoices ih         
 left outer join vwreexportsettlements vw on ih.companyid = vw.companyid and         
 ih.invoiceid = vw.invoiceid and ih.shopid = vw.shopid         
where         
 s.shopid = ih.shopid and  c.customerid = ih.customerid         
 and s.accountable is not null        
        
union all        
        
--15 hq receipt(Muliple Customer)        
select         
 rh.companyid, rh.departmentid, rd.customerid, rh.receiptdate tdate,'' as secref,         
 rh.receiptno tno, '' cr, 'Receipt' type, rh.remarks, 0.0  invamt,         
 rd.CustomerAmount pmtamt, null duedate, 0 age, rh.updatetime, null, 0.0 cinvamt,         
 isnull(convert(numeric(18,2), (rd.Amount * exchangerate)),0)  cpmtamt, financialid,         
 chequedetails, c.debtoraccid, 0.0 dinvamt, isnull(convert(numeric(18,2),         
 (rd.Amount * depexrate)),0)  dpmtamt,c.customercategory,        
 isnull(c.custgroupname,'')custgroupname,         
        rh.exchangerates, 0 SettledAmt,'' ,c.cusGroupID       
from         
 receiptvoucherheader rh, ReceiptVoucherCustomerDetails rd, acustomermaster c         
where         
 rh.receiptid=rd.ReceiptId and rh.Companyid=rd.Companyid and         
 rd.customerid=c.customerid and rh.cancelled = 0 and rh.receiptcustomerid is not null        
        
union all        
        
-- FOR TAKING THE ADJUSTMENT ENTRIES IN CUSTOMER BALANCE TO REMOVE THE DIFFERENCES        
select ah.CompanyId, ah.DepartmentId , ad.Customerid, 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 0 then ConsAmount else 0.00 end cBillAmt,         
 case JournalCredit when 1 then ConsAmount else 0.00 end  cPmtAmt, FinancialId, '',          
 DebtorAccId, case JournalCredit when 0 then ad.Amount else 0.00 end dBillAmt,         
 case JournalCredit when 1 then ad.Amount else 0.00 end dPmtAmt, v.customercategory,        
 isnull(v.custgroupname,'')custgroupname, ah.ExchangeRates, 0 SettledAmt,'',v.cusGroupID        
from         
        adjustmentheader ah, adjustmentdetails ad, aCustomerMaster v         
where         
        ah.AdjustmentID = ad.AdjustmentID         
        and ah.companyid = ad.companyid         
 and ah.Cancelled = 0         
        and  ad.Customerid is not null         
        and ad.Customerid = v.Customerid        
union all         
        
--MANAM UTILITY BILL        
        
SELECT         
 tbh.tbhCompanyid, tbh.tbhDepartmentid, tbh.tbhCustomerid, tbh.tbhBillDate,         
 refno as secref, tbh.tbhBillNo, '' cr, 'Utiliy Bill', tbh.tbhRemarks,         
 isnull(tbh.tbhAmount,0) BillAMt, 0 pmtamt, tbh.tbhDueDate duedate,         
 datediff(dd,tbh.tbhbilldate,getdate())  age,         
 tbh.tbhUpdateTime, vw.setdate, isnull(tbh.tbhAmount,0) * tbhExrate cbillamt, 0 cpmtamt,         
 v.FinancialId, '', DebtorAccId,        
 isnull(tbh.tbhAmount,0) * tbhdepexrate dbillamt, 0 dpmtamt,           
 c.customercategory, isnull(c.custgroupname,'')custgroupname, tbh.tbhExchangeRates,         
 isnull(vw.SettledAmt,0) SettledAmt ,tbh.tbhshopid ,c.cusGroupID       
FROM         
 losTenantServiceBillHeader tbh left outer join vwUtitilityBillSettlementNo vw        
 on tbh.tbhcompanyid = vw.companyid and tbh.tbhBillId = vw.invoiceid and         
 tbh.tbhshopid = vw.shopid, acustomermaster c, vwFinyearPeriod v        
WHERE         
 tbh.tbhCustomerID=c.customerID and tbh.tbhBankCashID is null and        
 tbh.tbhCancelled=0 and tbhcompanyid = v.companyid and        
 ( tbh.tbhbilldate between v.sdate and v.edate)        
        
union all        
        
--Room Billing Manaam         
SELECT         
 abh.abhCompanyid, abh.abhDepartmentid, abh.abhCustomerid, abh.abhBillDate,         
 vw.refno as secref, abh.abhBillNo, '' cr, 'Utiliy Bill', abh.abhRemarks,         
 isnull(abh.abhAmount,0) BillAMt, 0 pmtamt, abh.abhDueDate duedate,         
 datediff(dd,abh.abhbilldate,getdate()) age ,         
 abh.abhUpdateTime, vw.setdate, isnull(abh.abhAmount,0) * abhExrate cbillamt, 0 cpmtamt,         
 v.FinancialId, '', DebtorAccId,        
 isnull(abh.abhAmount,0) * abhdepexrate dbillamt, 0 dpmtamt,           
 c.customercategory, isnull(c.custgroupname,'')custgroupname, abh.abhExRates,         
 isnull(vw.SettledAmt,0) SettledAmt ,abh.abhshopid ,c.cusGroupID       
FROM         
 losApartmentBillHeader abh left outer join vwApartmentBillSettlementNo vw        
 on abh.abhcompanyid = vw.companyid and abh.abhBillId = vw.invoiceid and         
 abh.abhshopid = vw.shopid, acustomermaster c, vwFinyearPeriod v        
WHERE         
 abh.abhCustomerID=c.customerID and abh.abhCashAccId is null and        
 abh.abhCancelled=0 and abhcompanyid = v.companyid and        
 ( abh.abhbilldate between v.sdate and v.edate)
GO        
       

--************************************************************************
--************************************************************************
if exists( select * from sysobjects where id = object_id('dbo.vw_Report_Service_invoices'))
	begin
		drop view vw_Report_Service_invoices
	end
GO
--sp_helptext vw_Report_Service_invoices  
  
--Added the tables of rexporting to select in the transaction , inculded duedate field        
--Modified by  : Hariharan , Hariharan R        
--Modified Date  : 14/03/2004, 03/05/2004        
--Comments  : v3, included bonded customs duty calculations        
--   given specialinvoice chking        
--   : included sales person id selection in Simtec Service Invoices        
--   : Included ocd.IoAmount for grouping invoice query        
--------------------------------------------------------------------------------------        
CREATE VIEW vw_Report_Service_invoices as         
        
SELECT         
 AIH.CompanyID, 0 shopid, AIH.DepartmentID, AIH.InvoiceID, AIH.customerid,         
 AIH.invoicedate, AIH.invoiceno, isnull(aih.Referenceno,'') Referenceno, aih.remarks,        
 isnull(sum(ServiceQty * Amount),0)-isnull(AIH.Discount,0) as InvAmt ,'0 - 30' as Due,         
 'AI' AS Type ,'Trade Debtors' Debtortype,aih.updatetime, CustomerCategory,         
 dateadd(dd,isnull(aih.DuePeriod,0),aih.invoicedate) duedate,        
 Avg(aih.depexrate) as depexrate,5007 InterFaceID, 0 SalesPersonID,         
 c.CustomerType,0.0 DutyAmt,0.0 CostPrice ,CustGroupName ,c.cusGroupID      
FROM         
 acustomermaster c, AccountsInvoiceHeader AIH        
 Left outer join ServiceInvoiceDetails SID         
 on AIH.InvoiceID = SID.InvoiceID and AIH.CompanyID = SID.CompanyID         
WHERE         
 c.customerid = aih.customerid and AIH.CashInvoice = 0 and AIH.Proforma = 0 and         
 AIH.Cancelled = 0 and (datediff(dd,aIH.InvoiceDate,getdate())  between 0 and 30)          
group by         
 AIH.CompanyID, AIH.InvoiceID, AIH.customerid, AIH.DepartmentID,         
 AIH.invoicedate,AIH.invoiceno, aih.referenceno, aih.remarks,aih.updatetime,        
 AIH.Discount, customercategory, aih.dueperiod, c.CustomerType ,CustGroupName,c.cusGroupID      
having         
 isnull(sum(ServiceQty * Amount),0) - isnull(AIH.Discount,0) >0.0        
        
UNION ALL        
        
SELECT         
 AIH.CompanyID, 0 shopid, AIH.DepartmentID, AIH.InvoiceID,         
 AIH.customerid, AIH.invoicedate,AIH.invoiceno, isnull(aih.Referenceno,'') Referenceno,         
 aih.remarks,isnull(sum(ServiceQty * Amount),0)-isnull(AIH.Discount,0) as InvAmt,         
 '31 - 60' as Due  , 'AI' AS Type ,'Trade Debtors' Debtortype,aih.updatetime,         
 CustomerCategory, dateadd(dd,isnull(aih.DuePeriod,0),aih.invoicedate) duedate,        
 Avg(aih.depexrate) as depexrate,5007 InterFaceID, 0 SalesPersonID,        
 c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName,c.cusGroupID         
FROM         
 acustomermaster c, AccountsInvoiceHeader AIH        
 Left outer join ServiceInvoiceDetails SID         
 on AIH.InvoiceID = SID.InvoiceID and AIH.CompanyID = SID.CompanyID         
WHERE         
 c.customerid = aih.customerid and AIH.CashInvoice = 0 and AIH.Proforma = 0 and         
 AIH.Cancelled = 0 and (datediff(dd,aIH.InvoiceDate,getdate())  between 31 and 60)          
group by         
 AIH.CompanyID, AIH.InvoiceID, AIH.customerid, AIH.DepartmentID,         
 AIH.invoicedate,AIH.invoiceno, aih.referenceno, aih.remarks,aih.updatetime,        
 AIH.Discount, customercategory, aih.dueperiod,c.CustomerType ,CustGroupName ,c.cusGroupID      
having         
 isnull(sum(ServiceQty * Amount),0) - isnull(AIH.Discount,0) >0.0        
union all        
        
SELECT         
 AIH.CompanyID, 0 shopid, AIH.DepartmentID, AIH.InvoiceID, AIH.customerid,         
 AIH.invoicedate,AIH.invoiceno, isnull(aih.Referenceno,'') Referenceno, aih.remarks,        
 isnull(sum(ServiceQty * Amount),0)-isnull(AIH.Discount,0) as InvAmt,         
 '61 - 90' as Due  , 'AI' AS Type ,'Trade Debtors' Debtortype,aih.updatetime, customercategory,         
 dateadd(dd,isnull(aih.DuePeriod,0),aih.invoicedate) duedate,        
 Avg(aih.depexrate) as depexrate,5007 InterFaceID, 0 SalesPersonID,        
 c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,c.cusGroupID       
FROM         
 acustomermaster c, AccountsInvoiceHeader AIH        
 Left outer join ServiceInvoiceDetails SID         
 on AIH.InvoiceID = SID.InvoiceID and AIH.CompanyID = SID.CompanyID         
WHERE         
 c.customerid = aih.customerid and AIH.CashInvoice = 0 and AIH.Proforma = 0 and         
 AIH.Cancelled = 0 and (datediff(dd,aIH.InvoiceDate,getdate())  between 61 and 90)          
group by         
 AIH.CompanyID, AIH.InvoiceID, AIH.customerid, AIH.DepartmentID,         
 AIH.invoicedate,AIH.invoiceno, aih.referenceno, aih.remarks,aih.updatetime,        
 AIH.Discount, customercategory, aih.dueperiod,c.CustomerType,CustGroupName,c.cusGroupID       
having         
 isnull(sum(ServiceQty * Amount),0) - isnull(AIH.Discount,0) >0.0        
        
union all        
        
SELECT         
 AIH.CompanyID, 0 shopid, AIH.DepartmentID, AIH.InvoiceID,AIH.customerid,         
 AIH.invoicedate,AIH.invoiceno, isnull(aih.Referenceno,'') Referenceno, aih.remarks,        
 isnull(sum(ServiceQty * Amount),0)-isnull(AIH.Discount,0) as InvAmt,         
 ' > 90' as Due  , 'AI' AS Type ,'Trade Debtors' Debtortype,aih.updatetime, customercategory,         
 dateadd(dd,isnull(aih.DuePeriod,0),aih.invoicedate) duedate,         
 Avg(aih.depexrate) as depexrate,5007 InterFaceID, 0 SalesPersonID,        
 c.CustomerType, 0 DutyAmt,0.0 CostPrice  ,CustGroupName,c.cusGroupID       
FROM         
 acustomermaster c, AccountsInvoiceHeader AIH        
 Left outer join ServiceInvoiceDetails SID         
 on AIH.InvoiceID = SID.InvoiceID and AIH.CompanyID = SID.CompanyID         
WHERE         
 c.customerid = aih.customerid and AIH.CashInvoice = 0 and AIH.Proforma = 0 and         
 AIH.Cancelled = 0 and (datediff(dd,aIH.InvoiceDate,getdate())>90)          
group by         
 AIH.CompanyID, AIH.InvoiceID, AIH.customerid, AIH.DepartmentID, AIH.invoicedate,        
 AIH.invoiceno, aih.referenceno, aih.remarks,aih.updatetime,        
 AIH.Discount, customercategory, aih.dueperiod, c.CustomerType ,CustGroupName ,c.cusGroupID      
having         
 isnull(sum(ServiceQty * Amount),0) - isnull(AIH.Discount,0) >0.0        
        
union all        
        
--2. SHOP SERVICE INVOICE         
        
SELECT         
 AIH.aiCompanyID, aih.aishopid, AIH.aiDepartmentID, AIH.aiInvoiceID, AIH.aicustomerid,         
 AIH.aiinvoicedate,AIH.aiinvoiceno, isnull(aih.aiReferenceno,'') Referenceno,         
 aih.airemarks, Case convert(int, isnull(aiCashPaidByShop,0)) when 0 then         
 (sum(siServiceQty * siAmount)) -isnull(AIH.aiDiscount,0) else         
 (sum((siServiceQty * siAmount) + siClearingCommAmt) ) -isnull(AIH.aiDiscount,0) end         
 as InvAmt,         
 '0 - 30' as Due  , 'PSI' as type,'Trade Debtors' Debtortype, aih.updatetime, customercategory,         
 dateadd(dd,isnull(aih.aiDuePeriod,0), aih.aiinvoicedate) duedate,        
 Avg(aih.aidepexrate) as depexrate,1516 InterFaceID, 0 SalesPersonID,        
 c.CustomerType,0 DutyAmt,0.0 CostPrice  ,CustGroupName , c.cusGroupID    
FROM         
 ashops s, acustomermaster c, losAccountsInvoiceHeader AIH        
 Left outer join losServiceInvoiceDetails SID         
 on AIH.aiInvoiceID = SID.siInvoiceID and AIH.aiCompanyID = SID.siCompanyID and         
 aih.aishopid=sid.sishopid        
WHERE         
 s.shopid = aih.aishopid and s.accountable is not null and         
 c.customerid = aih.aicustomerid and AIH.aiCashInvoice = 0 and         
 AIH.aiProforma = 0 and AIH.aiCancelled = 0        
 and (datediff(dd,AIH.aiInvoiceDate,getdate()) between 0 and 30)          
GROUP BY         
 AIH.aiCompanyID, AIH.AISHOPID, AIH.aiInvoiceID , AIH.aicustomerid, AIH.aiDepartmentID,         
 AIH.aiinvoicedate, aih.updatetime,AIH.aiinvoiceno, aih.aiReferenceno, aih.airemarks,         
 AIH.aiDiscount, customercategory, aih.aidueperiod,c.CustomerType,CustGroupName,         
 convert(int, isnull(aiCashPaidByShop,0)) ,c.cusGroupID       
having         
 sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) >0.0        
union all        
        
SELECT         
 AIH.aiCompanyID, aih.aishopid, AIH.aiDepartmentID, AIH.aiInvoiceID, AIH.aicustomerid,         
 AIH.aiinvoicedate,AIH.aiinvoiceno, isnull(aih.aiReferenceno,'') Referenceno,          
 aih.airemarks,         
 Case convert(int, isnull(aiCashPaidByShop,0)) when 0 then         
 (sum(siServiceQty * siAmount)) -isnull(AIH.aiDiscount,0) else         
 (sum((siServiceQty * siAmount) + siClearingCommAmt) ) -isnull(AIH.aiDiscount,0) end        
  as InvAmt,         
 '31 - 60' as Due  , 'PSI' as type,'Trade Debtors' Debtortype, aih.updatetime,         
 customercategory, dateadd(dd,isnull(aih.aiDuePeriod,0), aih.aiinvoicedate) duedate,        
 Avg(aih.aidepexrate) as depexrate,1516 InterFaceID, 0 SalesPersonID,        
 c.CustomerType, 0.0 DutyAmt,0.0 CostPrice ,CustGroupName  ,c.cusGroupID     
FROM         
 ashops s, acustomermaster c, losAccountsInvoiceHeader AIH        
 Left outer join losServiceInvoiceDetails SID         
 on AIH.aiInvoiceID = SID.siInvoiceID and AIH.aiCompanyID = SID.siCompanyID and         
 aih.aishopid=sid.sishopid        
WHERE         
 s.shopid = aih.aishopid and s.accountable is not null and         
 c.customerid = aih.aicustomerid and AIH.aiCashInvoice = 0 and AIH.aiProforma = 0 and         
 AIH.aiCancelled = 0 and (datediff(dd,AIH.aiInvoiceDate,getdate()) between 31 and 60)          
GROUP BY         
 AIH.aiCompanyID, AIH.AISHOPID, AIH.aiInvoiceID , AIH.aicustomerid, AIH.aiDepartmentID,         
 AIH.aiinvoicedate, aih.updatetime,AIH.aiinvoiceno, aih.aiReferenceno, aih.airemarks,         
 AIH.aiDiscount, customercategory, aih.aidueperiod,c.CustomerType,CustGroupName,         
 convert(int, isnull(aiCashPaidByShop,0)) ,c.cusGroupID       
having         
 sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) >0.0        
union all        
        
SELECT         
 AIH.aiCompanyID, aih.aishopid, AIH.aiDepartmentID, AIH.aiInvoiceID, AIH.aicustomerid,         
 AIH.aiinvoicedate, AIH.aiinvoiceno, isnull(aih.aiReferenceno,'') Referenceno,         
 aih.airemarks,         
 Case convert(int, isnull(aiCashPaidByShop,0)) when 0 then         
 (sum(siServiceQty * siAmount)) -isnull(AIH.aiDiscount,0) else         
 (sum((siServiceQty * siAmount) + siClearingCommAmt) ) -isnull(AIH.aiDiscount,0) end        
  as InvAmt,          
 '61 - 90'  as Due  , 'PSI' as type,'Trade Debtors' Debtortype, aih.updatetime,         
 customercategory, dateadd(dd,isnull(aih.aiDuePeriod,0), aih.aiinvoicedate) duedate,        
 Avg(aih.aidepexrate) as depexrate,1516 InterFaceID, 0 SalesPersonID,        
 c.CustomerType, 0.0 DutyAmt,0.0 CostPrice ,CustGroupName ,c.cusGroupID       
FROM         
 ashops s, acustomermaster c, losAccountsInvoiceHeader AIH        
 Left outer join losServiceInvoiceDetails SID         
 on AIH.aiInvoiceID = SID.siInvoiceID and AIH.aiCompanyID = SID.siCompanyID and         
 aih.aishopid=sid.sishopid        
WHERE         
 s.shopid = aih.aishopid and s.accountable is not null and         
 c.customerid = aih.aicustomerid and AIH.aiCashInvoice = 0 and AIH.aiProforma = 0 and         
 AIH.aiCancelled = 0 and (datediff(dd,AIH.aiInvoiceDate,getdate()) between 61 and 90)          
GROUP BY         
 AIH.aiCompanyID, AIH.AISHOPID, AIH.aiInvoiceID , AIH.aicustomerid, AIH.aiDepartmentID,         
 AIH.aiinvoicedate, aih.updatetime,AIH.aiinvoiceno, aih.aiReferenceno, aih.airemarks,         
 AIH.aiDiscount, customercategory, aih.aidueperiod,c.CustomerType,CustGroupName,         
 convert(int, isnull(aiCashPaidByShop,0)),c.cusGroupID        
having         
 sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) >0.0        
union all        
        
SELECT         
 AIH.aiCompanyID, aih.aishopid, AIH.aiDepartmentID, AIH.aiInvoiceID, AIH.aicustomerid,         
 AIH.aiinvoicedate, AIH.aiinvoiceno,  isnull(aih.aiReferenceno,'') Referenceno,         
 aih.airemarks,         
 Case convert(int, isnull(aiCashPaidByShop,0)) when 0 then         
 (sum(siServiceQty * siAmount)) -isnull(AIH.aiDiscount,0) else         
 (sum((siServiceQty * siAmount) + siClearingCommAmt) ) -isnull(AIH.aiDiscount,0) end        
  as InvAmt,         
 ' > 90' as Due  , 'PSI' as type,'Trade Debtors' Debtortype, aih.updatetime,         
 customercategory, dateadd(dd,isnull(aih.aiDuePeriod,0), aih.aiinvoicedate) duedate,        
 Avg(aih.aidepexrate) as depexrate,1516 InterFaceID, 0 SalesPersonID,        
 c.CustomerType, 0.0 DutyAmt,0.0 CostPrice,CustGroupName,c.cusGroupID        
FROM         
 ashops s, acustomermaster c, losAccountsInvoiceHeader AIH        
 Left outer join losServiceInvoiceDetails SID         
 on AIH.aiInvoiceID = SID.siInvoiceID and AIH.aiCompanyID = SID.siCompanyID and         
 aih.aishopid=sid.sishopid        
WHERE         
 s.shopid = aih.aishopid and s.accountable is not null and         
 c.customerid = aih.aicustomerid and AIH.aiCashInvoice = 0         
 and AIH.aiProforma = 0 and AIH.aiCancelled = 0 and         
 (datediff(dd,AIH.aiInvoiceDate,getdate()) > 90)          
GROUP BY         
 AIH.aiCompanyID, AIH.AISHOPID, AIH.aiInvoiceID , AIH.aicustomerid,         
 AIH.aiDepartmentID, AIH.aiinvoicedate, aih.updatetime,        
 AIH.aiinvoiceno, aih.aiReferenceno, aih.airemarks, AIH.aiDiscount,         
 customercategory, aih.aidueperiod, c.CustomerType,CustGroupName,         
 convert(int, isnull(aiCashPaidByShop,0)),c.cusGroupID        
having         
 sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) >0.0        
        
union all        
        
--3. SHOP CREDIT INVOICE        
--isnull(sum(idunitprice),0) as InvAmt        
SELECT         
 IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,         
 IH.ihinvoicedate, iH.ihinvoiceno, isnull(ih.ihReferenceNo,'') Referenceno, ih.ihremarks,        
 case when s.futurevarchar ='B' and ih.ihdutypaidby='' then         
 (sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0))+isnull(sum(sid.idcdcustcur),0)        
 else (sum(isnull(SID.idunitprice,0))+ isnull(ocd.ioAmount,0))  end invAmt, '0 - 30' as Due  , 'PCI' as type,   'Trade Debtors' Debtortype, ih.updatetime, customercategory, ih.ihDueDate duedate,        
 avg(ih.ihdepexrate) as depExRate,1527 InterfaceID, ih.ihsalespersonid SalesPersonID,        
 c.CustomerType, sum(isnull(sid.idcdcustcur,0)) DutyAmt,        
 sum(isnull(idQuantity*idcostprice,0.0)) CostPrice  ,CustGroupName ,c.cusGroupID      
FROM         
 ashops s, acustomermaster c, losInvoiceHeader IH        
 Left outer join losInvoiceDetail SID         
 on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid        
 left outer join         
 (select        
  ioShopID,ioInvoiceID,sum(ioAmount) ioAmount        
 from        
  losInvoiceOC         
 group by        
  ioShopID,ioInvoiceID) ocd         
 on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID        
WHERE         
 s.shopid = ih.ihshopid and s.accountable is not null and         
 ih.ihcustomerid = c.customerid and IH.ihCashInvoice = 0 and IH.ihProforma = 0 and         
 IH.ihCancelled = 0 and IH.ihtype = 'i'         
 and (datediff(dd,IH.ihInvoiceDate,getdate()) between 0 and 30)          
GROUP BY         
 IH.ihCompanyID, IH.ihSHOPID, IH.ihInvoiceID , sID.idInvoiceID, IH.ihcustomerid,         
 IH.ihDepartmentID, IH.ihinvoicedate, ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo,         
 ih.ihremarks, IH.ihDiscount, customercategory, ih.ihDueDate ,IH.ihdutypaidby,        
 s.futurevarchar, ih.ihsalespersonid, c.CustomerType, ocd.ioAmount,CustGroupName ,c.cusGroupID       
UNION ALL        
--isnull(sum(idunitprice),0) as InvAmt        
SELECT         
 IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,         
 IH.ihinvoicedate, iH.ihinvoiceno,  isnull(ih.ihReferenceNo,'') Referenceno,         
 ih.ihremarks, case when  s.futurevarchar ='B' and ih.ihdutypaidby='' then         
 sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0)+isnull(sum(sid.idcdcustcur),0)        
 else sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0) end invAmt, '31 - 60' as Due  ,        
 'PCI' as type,'Trade Debtors' Debtortype, ih.updatetime, customercategory,         
 ih.ihDueDate duedate ,avg(ih.ihdepexrate) as depExRate,1527 InterfaceID,        
 ih.ihsalespersonid SalesPersonID,c.CustomerType, sum(isnull(sid.idcdcustcur,0)) DutyAmt,        
 sum(isnull(idQuantity*idcostprice,0.0)) CostPrice ,CustGroupName ,c.cusGroupID       
FROM         
 ashops s, acustomermaster c, losInvoiceHeader IH        
 Left outer join losInvoiceDetail SID         
 on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid        
 left outer join losInvoiceOC ocd        
 on ih.ihshopid = ocd.ioshopid and ih.ihinvoiceid = ocd.ioinvoiceid         
WHERE         
 s.shopid = ih.ihshopid and s.accountable is not null and         
 ih.ihcustomerid = c.customerid and IH.ihCashInvoice = 0         
 and IH.ihProforma = 0 and IH.ihCancelled = 0 and IH.ihtype = 'i'        
 and (datediff(dd,IH.ihInvoiceDate,getdate()) between 31 and 60)          
GROUP BY         
 IH.ihCompanyID, IH.ihSHOPID, IH.ihInvoiceID , sID.idInvoiceID, IH.ihcustomerid,         
 IH.ihDepartmentID, IH.ihinvoicedate, ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo,         
 ih.ihremarks, IH.ihDiscount, customercategory, ih.ihDueDate,IH.ihdutypaidby ,        
 s.futurevarchar, ih.ihsalespersonid, c.CustomerType, ocd.ioAmount ,CustGroupName ,c.cusGroupID     
        
UNION ALL        
--isnull(sum(idunitprice),0) as InvAmt,         
SELECT         
 IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,         
 IH.ihinvoicedate, iH.ihinvoiceno,  isnull(ih.ihReferenceNo,'') Referenceno,         
 ih.ihremarks,case when  s.futurevarchar ='B' and ih.ihdutypaidby='' then         
 sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0)+isnull(sum(sid.idcdcustcur),0)        
 else sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0)  end invAmt,'61 - 90' as Due  ,         
 'PCI' as type,'Trade Debtors' Debtortype, ih.updatetime, customercategory,         
 ih.ihDueDate duedate ,avg(ih.ihdepexrate) as depExRate,1527 InterfaceID,        
 ih.ihsalespersonid SalesPersonID,c.CustomerType, sum(isnull(sid.idcdcustcur,0)) DutyAmt,        
 sum(isnull(idQuantity*idcostprice,0)) CostPrice ,CustGroupName ,c.cusGroupID       
FROM         
 ashops s, acustomermaster c, losInvoiceHeader IH        
 Left outer join losInvoiceDetail SID         
 on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid        
 left outer join losInvoiceOC ocd        
 on ih.ihshopid = ocd.ioshopid and ih.ihinvoiceid = ocd.ioinvoiceid         
WHERE         
 s.shopid = ih.ihshopid and s.accountable is not null and         
 ih.ihcustomerid = c.customerid and IH.ihCashInvoice = 0 and IH.ihProforma = 0 and         
 IH.ihCancelled = 0 and IH.ihtype = 'i'        
 and (datediff(dd,IH.ihInvoiceDate,getdate()) between 61 and 90)          
GROUP BY         
 IH.ihCompanyID, IH.ihSHOPID, IH.ihInvoiceID , sID.idInvoiceID, IH.ihcustomerid,         
 IH.ihDepartmentID, IH.ihinvoicedate, ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo,         
 ih.ihremarks, IH.ihDiscount, customercategory, ih.ihDueDate ,IH.ihdutypaidby,        
 s.futurevarchar, ih.ihsalespersonid, c.CustomerType, ocd.ioAmount ,CustGroupName ,c.cusGroupID      
        
UNION ALL          
--isnull(sum(idunitprice),0) as InvAmt,         
SELECT         
 IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,         
 IH.ihinvoicedate, iH.ihinvoiceno,  isnull(ih.ihReferenceNo,'') Referenceno,         
 ih.ihremarks,case when s.futurevarchar ='B' and ih.ihdutypaidby='' then         
 sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0)+isnull(sum(sid.idcdcustcur),0)        
 else sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0) end invAmt,' > 90' as Due  ,         
 'PCI' as type,'Trade Debtors' Debtortype, ih.updatetime, customercategory,         
 ih.ihDueDate duedate ,avg(ih.ihdepexrate) as depExRate,1527 InterfaceID,        
 ih.ihsalespersonid SalesPersonID,c.CustomerType, sum(isnull(sid.idcdcustcur,0)) DutyAmt,        
 sum(isnull(idQuantity*idcostprice,0)) CostPrice,CustGroupName ,c.cusGroupID        
FROM         
 ashops s, acustomermaster c, losInvoiceHeader IH        
 Left outer join losInvoiceDetail SID         
 on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid        
 left outer join losInvoiceOC ocd        
 on ih.ihshopid = ocd.ioshopid and ih.ihinvoiceid = ocd.ioinvoiceid         
WHERE         
 s.shopid = ih.ihshopid and s.accountable is not null and         
 ih.ihcustomerid = c.customerid and IH.ihCashInvoice = 0 and IH.ihProforma = 0 and         
 IH.ihCancelled = 0 and IH.ihtype = 'i' and (datediff(dd,IH.ihInvoiceDate,getdate()) > 90)          
GROUP BY         
 IH.ihCompanyID, IH.ihSHOPID, IH.ihInvoiceID , sID.idInvoiceID, IH.ihcustomerid,         
 IH.ihDepartmentID, IH.ihinvoicedate, ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo,         
 ih.ihremarks, IH.ihDiscount, customercategory, ih.ihDueDate ,IH.ihdutypaidby,        
 s.futurevarchar, ih.ihsalespersonid, c.CustomerType, ocd.ioAmount  ,CustGroupName ,c.cusGroupID     
        
union all        
--4. SHOP SPECIAL INVOICE        
SELECT         
 IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,         
 IH.ihinvoicedate,  iH.ihinvoiceno, isnull(ih.IhReferenceNo,'') referenceno,         
 ih.ihremarks, isnull(sum(case when idratetype =1 then         
 -idunitprice else idunitprice end),0) as InvAmt,         
 '0 - 30' as Due  , 'PDI' as type,'Trade Debtors' Debtortype, ih.updatetime,         
 customercategory, ih.IhDueDate duedate,avg(ih.ihdepexrate) as depExRate,        
 5008 interfaceID,ih.ihsalespersonid SalesPersonID,c.CustomerType,0.0 DutyAmt,        
 sum(isnull(idQuantity*idcostprice,0)) CostPrice ,CustGroupName ,c.cusGroupID      
FROM         
 ashops s, acustomermaster c, losSpecialInvoiceHeader IH        
 Left outer join losSpecialInvoiceDetail SID         
 on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid and idratetype =0        
WHERE         
 s.shopid = ih.ihshopid and s.accountable is not null and         
 ih.ihcustomerid = c.customerid and IH.ihCashInvoice = 0 and IH.ihProforma = 0 and         
 IH.ihCancelled = 0 and (datediff(dd,IH.ihInvoiceDate,getdate()) between 0 and 30)        
 and ih.ihtransfinished=1        
GROUP BY         
 IH.ihCompanyID, IH.ihSHOPID, IH.ihInvoiceID, IH.ihcustomerid, IH.ihinvoicedate,         
 ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo, ih.ihremarks,        
 IH.ihDepartmentID, IH.ihDiscount, customercategory, ih.IhDueDate,ih.ihsalespersonid,        
 c.CustomerType  ,CustGroupName,c.cusGroupID      
        
union all        
        
SELECT         
 IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,         
 IH.ihinvoicedate,  iH.ihinvoiceno,  isnull(ih.IhReferenceNo,'') referenceno,         
 ih.ihremarks, isnull(sum(case when idratetype =1         
 then -idunitprice else idunitprice end),0) as InvAmt, '31 - 60' as Due  ,         
 'PDI' as type,'Trade Debtors' Debtortype, ih.updatetime, customercategory,         
 ih.IhDueDate duedate,avg(ih.ihdepexrate) as depExRate,5008 interfaceID,        
 ih.ihsalespersonid SalesPersonID,c.CustomerType,0.0 DutyAmt,        
 sum(isnull(idQuantity*idcostprice,0)) CostPrice ,CustGroupName,c.cusGroupID       
FROM         
 ashops s, acustomermaster c, losSpecialInvoiceHeader IH        
 Left outer join losSpecialInvoiceDetail SID         
 on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid and idratetype =0        
WHERE         
 s.shopid = ih.ihshopid and s.accountable is not null and         
 ih.ihcustomerid = c.customerid and IH.ihCashInvoice = 0 and IH.ihProforma = 0 and         
 IH.ihCancelled = 0 and (datediff(dd,IH.ihInvoiceDate,getdate()) between 31 and 60)        
 and ih.ihtransfinished=1        
GROUP BY         
 IH.ihCompanyID, IH.ihSHOPID, IH.ihInvoiceID, IH.ihcustomerid, IH.ihinvoicedate,         
 ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo, ih.ihremarks,IH.ihDepartmentID,         
 IH.ihDiscount, customercategory, ih.IhDueDate,ih.ihsalespersonid,c.CustomerType ,CustGroupName,c.cusGroupID      
        
union all        
        
SELECT         
 IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,         
 IH.ihinvoicedate,  iH.ihinvoiceno,  isnull(ih.IhReferenceNo,'') referenceno,         
 ih.ihremarks, isnull(sum(case when idratetype =1         
 then -idunitprice else idunitprice end),0) as InvAmt, '61 - 90' as Due  ,         
 'PDI' as type,'Trade Debtors' Debtortype, ih.updatetime, customercategory,         
 ih.IhDueDate duedate,avg(ih.ihdepexrate) as depExRate,5008 interfaceID,        
 ih.ihsalespersonid,c.CustomerType, 0.0 DutyAmt,        
 sum(isnull(idQuantity*idcostprice,0)) CostPrice ,CustGroupName,c.cusGroupID        
FROM         
 ashops s, acustomermaster c, losSpecialInvoiceHeader IH        
 Left outer join losSpecialInvoiceDetail SID         
 on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid and idratetype =0        
WHERE         
 s.shopid = ih.ihshopid and s.accountable is not null and         
 ih.ihcustomerid = c.customerid and IH.ihCashInvoice = 0 and IH.ihProforma = 0 and         
 IH.ihCancelled = 0 and (datediff(dd,IH.ihInvoiceDate,getdate()) between 61 and 90)        
 and ih.ihtransfinished=1        
GROUP BY         
 IH.ihCompanyID, IH.ihSHOPID, IH.ihInvoiceID, IH.ihcustomerid, IH.ihinvoicedate,         
 ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo, ih.ihremarks,        
 IH.ihDepartmentID, IH.ihDiscount, customercategory, ih.IhDueDate,ih.ihsalespersonid,        
 c.CustomerType ,CustGroupName,c.cusGroupID       
        
union all        
        
SELECT         
 IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,         
 IH.ihinvoicedate,  iH.ihinvoiceno,  isnull(ih.IhReferenceNo,'') referenceno,         
 ih.ihremarks, isnull(sum(case when idratetype =1         
 then -idunitprice else idunitprice end),0) as InvAmt, ' > 90' as Due  ,         
 'PDI' as type,'Trade Debtors' Debtortype, ih.updatetime, customercategory,         
 ih.IhDueDate duedate ,avg(ih.ihdepexrate) as depExRate,5008 interfaceID,        
 ih.ihsalespersonid SalesPersonID, c.CustomerType,0.0 DutyAmt,        
 sum(isnull(idQuantity*idcostprice,0)) CostPrice ,CustGroupName ,c.cusGroupID       
FROM         
 ashops s, acustomermaster c, losSpecialInvoiceHeader IH        
 Left outer join losSpecialInvoiceDetail SID         
 on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid and idratetype =0        
WHERE         
 s.shopid = ih.ihshopid and s.accountable is not null and         
 ih.ihcustomerid = c.customerid and IH.ihCashInvoice = 0 and IH.ihProforma = 0 and         
 IH.ihCancelled = 0 and (datediff(dd,IH.ihInvoiceDate,getdate()) >90)        
 and ih.ihtransfinished=1        
GROUP BY         
 IH.ihCompanyID, IH.ihSHOPID, IH.ihInvoiceID, IH.ihcustomerid, IH.ihinvoicedate,         
 ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo, ih.ihremarks,IH.ihDepartmentID,         
 IH.ihDiscount, customercategory, ih.IhDueDate,ih.ihsalespersonid,c.CustomerType  ,CustGroupName,c.cusGroupID      
        
union all        
        
--5. debit note from hq        
        
SELECT         
 dcn.DCNCompanyid, 0 shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNCustomerID,         
 dcn.DCNDate, dcn.DCNNo, isnull(dcn.DCNReferenceNo,'') referenceno, dcn.DCNDetails,         
 DCNAmount as InvAmt, '0 - 30'  as Due, 'DCN' as type,'Trade Debtors' Debtortype,         
 dcn.updatetime, customercategory, dcn.dcndate duedate,        
 avg(dcn.dcndepexrate) as depExRate,5010 InterfaceID, 0 SalesPersonID,        
 c.CustomerType, 0.0 DutyAmt,0.0 CostPrice ,CustGroupName,c.cusGroupID       
FROM         
 acustomermaster c, debitcreditnote dcn        
WHERE         
 dcn.dcncustomerid = c.customerid and dcn.DCNCustomerID is not null and         
 dcn.DCNDebit =1 and dcn.DCNCancelled= 0 and         
 (datediff(dd,dcn.dcnDate,getdate()) between 0 and 30)        
GROUP BY         
 dcn.dcncompanyid, dcn.dcnid, dcn.dcncustomerid, dcn.dcndate, dcn.updatetime,         
 dcn.dcnno, dcn.DCNReferenceNo, dcn.dcndetails,dcn.dcnDepartmentID, dcn.dcnamount,          
 customercategory,c.CustomerType  ,CustGroupName ,c.cusGroupID     
        
union all        
        
SELECT         
 dcn.DCNCompanyid, 0 shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNCustomerID,         
 dcn.DCNDate,dcn.DCNNo, isnull(dcn.DCNReferenceNo,'') referenceno, dcn.DCNDetails,         
 DCNAmount as InvAmt,'31 - 60'  as Due, 'DCN' as type,'Trade Debtors' Debtortype,         
 dcn.updatetime, customercategory , dcn.dcndate duedate,        
 avg(dcn.dcndepexrate) as depExRate,5010 InterfaceID, 0 SalesPersonID,        
 c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName ,c.cusGroupID      
FROM         
 acustomermaster c, debitcreditnote dcn        
WHERE         
 c.customerid = dcn.dcncustomerid and dcn.DCNCustomerID is not null and         
 dcn.DCNDebit =1 and dcn.DCNCancelled= 0 and         
 (datediff(dd,dcn.dcnDate,getdate()) between 31 and 60)        
GROUP BY         
 dcn.dcncompanyid, dcn.dcnid, dcn.dcncustomerid, dcn.dcndate, dcn.updatetime,         
 dcn.dcnno, dcn.DCNReferenceNo, dcn.dcndetails,dcn.dcnDepartmentID, dcn.dcnamount,         
 customercategory, c.CustomerType  ,CustGroupName ,c.cusGroupID     
        
union all        
        
SELECT         
 dcn.DCNCompanyid, 0 shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNCustomerID,         
 dcn.DCNDate, dcn.DCNNo, isnull(dcn.DCNReferenceNo,'') referenceno, dcn.DCNDetails,         
 DCNAmount as InvAmt,'61 - 90'  as Due, 'DCN' as type,'Trade Debtors' Debtortype,         
 dcn.updatetime, customercategory , dcn.dcndate duedate,        
 avg(dcn.dcndepexrate) as depExRate,5010 InterfaceID, 0 SalesPersonID,        
 c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName ,c.cusGroupID      
FROM         
 acustomermaster c, debitcreditnote dcn        
WHERE         
 c.customerid = dcn.dcncustomerid and dcn.DCNCustomerID is not null and         
 dcn.DCNDebit =1 and dcn.DCNCancelled= 0         
 and (datediff(dd,dcn.dcnDate,getdate()) between 61 and 90)        
GROUP BY         
 dcn.dcncompanyid, dcn.dcnid, dcn.dcncustomerid, dcn.dcndate, dcn.updatetime,         
 dcn.dcnno, dcn.DCNReferenceNo, dcn.dcndetails,dcn.dcnDepartmentID, dcn.dcnamount,         
 customercategory,c.CustomerType ,CustGroupName,c.cusGroupID       
        
union all        
        
SELECT         
 dcn.DCNCompanyid, 0 shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNCustomerID,         
 dcn.DCNDate, dcn.DCNNo, isnull(dcn.DCNReferenceNo,'') referenceno, dcn.DCNDetails,         
 DCNAmount as InvAmt,' > 90'  as Due, 'DCN' as type,'Trade Debtors' Debtortype,         
 dcn.updatetime, customercategory, dcn.dcndate duedate,        
 avg(dcn.dcndepexrate) as depExRate,5010 InterfaceID, 0 SalesPersonID,        
 c.CustomerType, 0.0 DutyAmt,0.0 CostPrice ,CustGroupName ,c.cusGroupID      
FROM         
 acustomermaster c, debitcreditnote dcn        
WHERE         
 c.customerid = dcn.dcncustomerid and dcn.DCNCustomerID is not null and         
 dcn.DCNDebit =1 and dcn.DCNCancelled= 0         
 and (datediff(dd,dcn.dcnDate,getdate()) > 90)         
GROUP BY         
 dcn.dcncompanyid, dcn.dcnid, dcn.dcncustomerid, dcn.dcndate, dcn.updatetime,         
 dcn.dcnno, dcn.DCNReferenceNo, dcn.dcndetails,dcn.dcnDepartmentID, dcn.dcnamount,         
 customercategory, c.CustomerType,CustGroupName ,c.cusGroupID       
        
union all        
        
-- payment to customer considered as invoice        
select         
 ph.phcompanyid, 0 shopid, ph.phdepartmentid, ph.phpaymentid, ph.phcustomerid,         
 ph.phpaymentdate,  ph.phpaymentno, isnull(ph.phcbreferenceno,'') referenceno,         
 ph.phremarks, ph.phcustomeramount, '0 - 30' due,  'rf' type,'Other Debtors' Debtortype,         
 ph.updatetime, customercategory, ph.phpaymentdate duedate,        
 ph.phdepexrate as depExRate,5005 InterfaceID, 0 SalesPersonID,        
 c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName ,c.cusGroupID      
from         
 acustomermaster c, ahqpaymentvoucherheader ph         
where         
 c.customerid = ph.phcustomerid and ph.phcancelled =0 and phcustomerid is not null and         
 (getdate() - ph.phpaymentdate between 0 and 30)        
        
union all        
        
select         
 ph.phcompanyid, 0 shopid, ph.phdepartmentid, ph.phpaymentid, ph.phcustomerid,         
 ph.phpaymentdate,  ph.phpaymentno, isnull(ph.phcbreferenceno,'') referenceno,         
 ph.phremarks,  ph.phcustomeramount, '31 - 60' due,  'rf' type,        
 'Other Debtors' Debtortype, ph.updatetime, customercategory, ph.phpaymentdate duedate,        
 ph.phdepexrate as depExRate,5005 InterfaceID, 0 SalesPersonID,        
 c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,c.cusGroupID       
from         
 acustomermaster c, ahqpaymentvoucherheader ph         
where         
 c.customerid = ph.phcustomerid and ph.phcancelled =0 and phcustomerid is not null and         
 (getdate() - ph.phpaymentdate between 31 and 60)        
        
union all        
        
select         
 ph.phcompanyid, 0 shopid, ph.phdepartmentid, ph.phpaymentid, ph.phcustomerid,         
 ph.phpaymentdate,  ph.phpaymentno, isnull(ph.phcbreferenceno,'') referenceno,         
 ph.phremarks, ph.phcustomeramount, '61 - 90' due,  'rf' type,        
 'Other Debtors' Debtortype, ph.updatetime, customercategory, ph.phpaymentdate duedate,        
 ph.phdepexrate as depExRate,5005 InterfaceID, 0 SalesPersonID,        
 c.CustomerType, 0.0 DutyAmt,0.0 CostPrice ,CustGroupName,c.cusGroupID       
from         
 acustomermaster c, ahqpaymentvoucherheader ph         
where         
 c.customerid = ph.phcustomerid and ph.phcancelled =0 and phcustomerid is not null and         
 (getdate() - ph.phpaymentdate between 61 and 90)         
        
union all        
        
select         
 ph.phcompanyid, 0 shopid, ph.phdepartmentid, ph.phpaymentid, ph.phcustomerid,         
 ph.phpaymentdate,  ph.phpaymentno, isnull(ph.phcbreferenceno,'') referenceno,         
 ph.phremarks, ph.phcustomeramount, ' > 90' due,  'rf' type,'Other Debtors' Debtortype,         
 ph.updatetime, customercategory, ph.phpaymentdate duedate,        
 ph.phdepexrate as depExRate,5005 InterfaceID, 0 SalesPersonID,        
 c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName ,c.cusGroupID      
from         
 acustomermaster c, ahqpaymentvoucherheader ph         
where         
 c.customerid = ph.phcustomerid and ph.phcancelled =0 and phcustomerid is not null and         
 (getdate() - ph.phpaymentdate > 90)        
        
union all        
-- for booking service invoices hari 020319        
SELECT         
 IH.CompanyID, ih.shopid, IH.serinvhdepartmentid, IH.invoiceid, IH.customerid,         
 IH.invoicedate, iH.invoiceno, isnull(ih.referenceno,''), ih.remarks, serinvhamount,         
 '0 - 30' as Due  , 'SBI' as type,'Trade Debtors' Debtortype, ih.serinvhupdatetime,         
 customercategory, IH.invoicedate duedate,ih.seinvhdepexrate as depExRate,        
 1802 InterfaceID,  serinvhpreparedby SalesPersonID, c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName   ,c.cusGroupID    
FROM         
 ashops s, acustomermaster c,  vwbookingservinvoices IH         
where         
 s.shopid = ih.shopid and s.accountable is not null and c.customerid = ih.customerid and        
 datediff(dd,IH.InvoiceDate,getdate()) between 0 and 30        
        
union all        
        
SELECT         
 IH.CompanyID, ih.shopid, IH.serinvhdepartmentid, IH.invoiceid, IH.customerid,         
 IH.invoicedate, iH.invoiceno, isnull(ih.referenceno,''), ih.remarks, serinvhamount,         
 '31 - 60' as Due  , 'SBI' as type,'Trade Debtors' Debtortype, ih.serinvhupdatetime        
 , customercategory, IH.invoicedate duedate,ih.seinvhdepexrate as depExRate,        
 1802 InterfaceID, serinvhpreparedby SalesPersonID, c.CustomerType, 0.0 DutyAmt,0.0 CostPrice ,CustGroupName   ,c.cusGroupID    
FROM         
 ashops s, acustomermaster c, vwbookingservinvoices IH         
where         
 s.shopid = ih.shopid and s.accountable is not null and         
 c.customerid = ih.customerid and         
 datediff(dd,IH.InvoiceDate,getdate()) between 31 and 60        
        
union all        
        
SELECT         
 IH.CompanyID, ih.shopid, IH.serinvhdepartmentid, IH.invoiceid, IH.customerid,         
 IH.invoicedate, iH.invoiceno, isnull(ih.referenceno,''), ih.remarks, serinvhamount,         
 '61 - 90' as Due  , 'SBI' as type,'Trade Debtors' Debtortype, ih.serinvhupdatetime,         
 customercategory, IH.invoicedate duedate,ih.seinvhdepexrate as depExRate,        
 1802 InterfaceID, serinvhpreparedby SalesPersonID, c.CustomerType, 0.0 DutyAmt,0.0 CostPrice ,CustGroupName   ,c.cusGroupID    
FROM         
 ashops s, acustomermaster c, vwbookingservinvoices IH where s.shopid = ih.shopid and s.accountable is not null and         
 c.customerid = ih.customerid and datediff(dd,IH.InvoiceDate,getdate()) between 61 and 90        
        
union all        
        
SELECT         
 IH.CompanyID, ih.shopid, IH.serinvhdepartmentid, IH.invoiceid, IH.customerid,         
 IH.invoicedate, iH.invoiceno, isnull(ih.referenceno,''), ih.remarks, serinvhamount,         
 ' > 90' as Due  , 'SBI' as type,'Trade Debtors' Debtortype, ih.serinvhupdatetime,         
 customercategory, IH.invoicedate duedate,ih.seinvhdepexrate as depExRate,        
 1802 InterfaceID, serinvhpreparedby SalesPersonID, c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName   ,c.cusGroupID    
FROM         
 ashops s, acustomermaster c, vwbookingservinvoices IH         
where         
 s.shopid = ih.shopid and s.accountable is not null and c.customerid = ih.customerid and        
 datediff(dd,IH.InvoiceDate,getdate()) > 90        
        
union all        
-- for shop debit credit note        
SELECT         
 losdcnCompanyID, losdcnshopid, losdcndepartmentid, losdcnid, losdcncustomerid,         
 losdcndate, losdcnno, isnull(losreferenceno,''), losdcnremarks, losdcnamount,         
 '0 - 30' as Due  , 'sdcn' as type,'Trade Debtors' Debtortype, updatetime,         
 customercategory, losdcndate, losdepexrate as depExRate,1517 InterfaceID,        
 0 SalesPersonID, c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName ,c.cusGroupID      
FROM         
 ashops s, acustomermaster c, losdebitcreditnote         
where         
 s.shopid = losdcnshopid and s.accountable is not null and         
 c.customerid = losdcncustomerid and losdcncancelled =0 and losdcndebit =1 and         
 losdcncustomerid is not null and datediff(dd,losdcnDate,getdate()) between 0 and 30        
        
union all        
-- for shop debit credit note        
SELECT         
 losdcnCompanyID, losdcnshopid, losdcndepartmentid, losdcnid, losdcncustomerid,         
 losdcndate, losdcnno, isnull(losreferenceno,''), losdcnremarks, losdcnamount,         
 '31 - 60' as Due  , 'sdcn' as type,'Trade Debtors' Debtortype, updatetime,         
 customercategory, losdcndate, losdepexrate as depExRate,1517 InterfaceID,        
 0 SalesPersonID, c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName ,c.cusGroupID      
FROM         
 ashops s, acustomermaster c, losdebitcreditnote         
where         
 s.shopid = losdcnshopid and s.accountable is not null and         
 c.customerid = losdcncustomerid and losdcncustomerid is not null and         
 losdcncancelled =0 and losdcndebit =1 and         
 datediff(dd,losdcnDate,getdate()) between 31 and 60        
        
union all        
-- for shop debit credit note        
SELECT         
 losdcnCompanyID, losdcnshopid, losdcndepartmentid, losdcnid, losdcncustomerid,         
 losdcndate, losdcnno, isnull(losreferenceno,''), losdcnremarks, losdcnamount,         
 '61 - 90' as Due  , 'sdcn' as type,'Trade Debtors' Debtortype, updatetime,         
 customercategory, losdcndate, losdepexrate as depExRate,1517 InterfaceID,        
 0 SalesPersonID, c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,c.cusGroupID       
FROM         
 ashops s, acustomermaster c, losdebitcreditnote         
where         
 s.shopid = losdcnshopid and s.accountable is not null and         
 c.customerid = losdcncustomerid and losdcncustomerid is not null and         
 losdcncancelled =0 and losdcndebit =1 and          
 datediff(dd,losdcnDate,getdate()) between 61 and 90        
        
union all        
-- for shop debit credit note        
SELECT         
 losdcnCompanyID, losdcnshopid, losdcndepartmentid, losdcnid, losdcncustomerid,         
 losdcndate, losdcnno, isnull(losreferenceno,''), losdcnremarks, losdcnamount,         
 ' > 90' as Due  , 'sdcn' as type,'Trade Debtors' Debtortype, updatetime,         
 customercategory, losdcndate, losdepexrate as depExRate,1517 InterfaceID,        
 0 SalesPersonID,c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName  ,c.cusGroupID     
FROM         
 ashops s, acustomermaster c, losdebitcreditnote         
where         
 s.shopid = losdcnshopid and s.accountable is not null and         
 c.customerid = losdcncustomerid and losdcncustomerid is not null and         
 losdcncancelled =0 and losdcndebit =1         
 and  datediff(dd,losdcnDate,getdate()) > 90        
        
union all        
        
SELECT         
 IH.reHCompanyID, ih.reHshopid, IH.reHDepartmentID, IH.reHExportID, IH.rehcustomerid,         
 IH.rehExportdate, iH.rehExportNo, isnull(ih.rehReferenceNo,'') Referenceno,         
 ih.rehremarks,isnull(sum(rehExportAmount),0) as InvAmt, '0 - 30' as Due  ,         
 'RE' as type,'Trade Debtors' Debtortype, ih.rehupdatetime, customercategory,         
 rehDueDate duedate,avg(ih.rehDepExRate) as depExRate,1529 InterfaceID,        
 ih.rehSalesPersonID SalesPersonID, c.CustomerType, 0.0 DutyAmt,        
 sum(isnull(redQuantity * redCostPrice,0)) CostPrice  ,CustGroupName  ,c.cusGroupID     
FROM         
 ashops s, acustomermaster c,   losExportHeader IH        
 Left outer join losExportDetail SID         
 on IH.rehExportID = SID.redExportID and ih.reHshopid=sid.redshopid        
WHERE         
 s.shopid = ih.rehshopid and s.accountable is not null and         
 ih.rehcustomerid = c.customerid and IH.rehCashInvoice = 0 and IH.rehProforma = 0 and         
 IH.rehCancelled = 0 and IH.rehtype = 'i' and rehcustomerid is not null and         
 (datediff(dd,IH.rehExportDate,getdate()) between 0 and 30)          
GROUP BY         
 IH.rehCompanyID, IH.rehSHOPID, IH.rehExportID , sID.redExportID, IH.rehcustomerid,         
 IH.rehDepartmentID, IH.rehExportDate, ih.rehupdatetime, iH.rehExportNo,         
 ih.rehReferenceNo, ih.rehremarks, IH.rehDiscount, customercategory, rehDueDate ,        
 ih.rehSalesPersonID,c.CustomerType ,CustGroupName  ,c.cusGroupID     
        
union all        
        
SELECT         
 IH.reHCompanyID, ih.reHshopid, IH.reHDepartmentID, IH.reHExportID, IH.rehcustomerid,         
 IH.rehExportdate, iH.rehExportNo, isnull(ih.rehReferenceNo,'') Referenceno,         
 ih.rehremarks,isnull(sum(redunitprice),0) as InvAmt, '31 - 60' as Due  ,         
 'RE' as type,'Trade Debtors' Debtortype, ih.rehupdatetime, customercategory,         
 rehDueDate duedate,avg(ih.rehDepExRate) as depExRate,1529 InterfaceID,        
 ih.rehSalesPersonID SalesPersonID, c.CustomerType, 0.0 DutyAmt,        
 sum(isnull(redQuantity * redCostPrice,0)) CostPrice  ,CustGroupName  ,c.cusGroupID     
FROM         
 ashops s, acustomermaster c, losExportHeader IH        
 Left outer join losExportDetail SID         
 on IH.rehExportID = SID.redExportID and ih.reHshopid=sid.redshopid        
WHERE         
 s.shopid = ih.rehshopid and s.accountable is not null and         
 ih.rehcustomerid = c.customerid and IH.rehCashInvoice = 0 and IH.rehProforma = 0 and         
 IH.rehCancelled = 0 and IH.rehtype = 'i' and         
 (datediff(dd,IH.rehExportDate,getdate()) between 31 and 60)          
 and rehcustomerid is not null        
GROUP BY         
 IH.rehCompanyID, IH.rehSHOPID, IH.rehExportID , sID.redExportID, IH.rehcustomerid,         
 IH.rehDepartmentID, IH.rehExportDate, ih.rehupdatetime, iH.rehExportNo,         
 ih.rehReferenceNo, ih.rehremarks, IH.rehDiscount, customercategory, rehDueDate ,        
 ih.rehSalesPersonID, c.CustomerType ,CustGroupName ,c.cusGroupID       
        
union all        
        
SELECT          IH.reHCompanyID, ih.reHshopid, IH.reHDepartmentID, IH.reHExportID, IH.rehcustomerid,         
 IH.rehExportdate, iH.rehExportNo, isnull(ih.rehReferenceNo,'') Referenceno,         
 ih.rehremarks,isnull(sum(redunitprice),0) as InvAmt,         
 '61 - 90' as Due  , 'RE' as type,'Trade Debtors' Debtortype, ih.rehupdatetime,         
 customercategory, rehDueDate duedate,avg(ih.rehDepExRate) as depExRate,1529 InterfaceID,        
 ih.rehSalesPersonID SalesPersonID, c.CustomerType, 0.0 DutyAmt,        
 sum(isnull(redQuantity * redCostPrice,0)) CostPrice  ,CustGroupName ,c.cusGroupID      
FROM         
 ashops s, acustomermaster c, losExportHeader IH        
 Left outer join losExportDetail SID         
 on IH.rehExportID = SID.redExportID and ih.reHshopid=sid.redshopid        
WHERE         
 s.shopid = ih.rehshopid and s.accountable is not null and         
 ih.rehcustomerid = c.customerid and IH.rehCashInvoice = 0 and IH.rehProforma = 0 and         
 IH.rehCancelled = 0 and IH.rehtype = 'i' and rehcustomerid is not null        
 and (datediff(dd,IH.rehExportDate,getdate()) between 61 and 90)          
GROUP BY         
 IH.rehCompanyID, IH.rehSHOPID, IH.rehExportID , sID.redExportID, IH.rehcustomerid,         
 IH.rehDepartmentID, IH.rehExportDate, ih.rehupdatetime, iH.rehExportNo,         
 ih.rehReferenceNo, ih.rehremarks, IH.rehDiscount, customercategory, rehDueDate,        
 ih.rehSalesPersonID, c.CustomerType ,CustGroupName ,c.cusGroupID       
union all        
        
SELECT         
 IH.reHCompanyID, ih.reHshopid, IH.reHDepartmentID, IH.reHExportID, IH.rehcustomerid,         
 IH.rehExportdate, iH.rehExportNo, isnull(ih.rehReferenceNo,'') Referenceno, ih.rehremarks,        
 isnull(sum(redunitprice),0) as InvAmt,         
 '> 90' as Due  , 'RE' as type,'Trade Debtors' Debtortype, ih.rehupdatetime,         
 customercategory, rehDueDate duedate,avg(ih.rehDepExRate) as depExRate,1529 InterfaceID,        
 ih.rehSalesPersonID SalesPersonID, c.CustomerType, 0 DutyAmt,        
 sum(isnull(redQuantity * redCostPrice,0)) CostPrice,CustGroupName,c.cusGroupID       
FROM         
 ashops s, acustomermaster c, losExportHeader IH        
 Left outer join losExportDetail SID         
 on IH.rehExportID = SID.redExportID and ih.reHshopid=sid.redshopid        
WHERE         
 s.shopid = ih.rehshopid and s.accountable is not null and         
 ih.rehcustomerid = c.customerid and IH.rehCashInvoice = 0 and IH.rehProforma = 0 and         
 IH.rehCancelled = 0 and IH.rehtype = 'i' and rehcustomerid is not null and         
 (datediff(dd,IH.rehExportDate,getdate()) > 90)          
GROUP BY         
 IH.rehCompanyID, IH.rehSHOPID, IH.rehExportID , sID.redExportID, IH.rehcustomerid,         
 IH.rehDepartmentID, IH.rehExportDate, ih.rehupdatetime, iH.rehExportNo,         
 ih.rehReferenceNo, ih.rehremarks, IH.rehDiscount, customercategory, rehDueDate ,        
 ih.rehSalesPersonID, c.CustomerType ,CustGroupName ,c.cusGroupID      
        
UNION ALL        
--Room Billing Manaam         
SELECT         
 abh.abhCompanyid, abhSHopID shopid, abh.abhDepartmentid, abh.abhBillId,        
 abh.abhCustomerid, abh.abhBillDate, abh.abhBillNo, isnull(abh.abhReferenceno,'')         
 Referenceno, abh.abhRemarks, (abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn)        
 as InvAmt ,'0 - 30' as Due, 'RBI' AS Type ,'Trade Debtors' Debtortype,        
 abh.abhUpdateTime, CustomerCategory, abh.abhDueDate duedate,         
 abh.abhDepExRate as depexrate,2304 InterFaceID,         
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice ,CustGroupName ,c.cusGroupID      
FROM         
 losApartmentBillHeader abh, acustomermaster c        
WHERE         
 abh.abhCustomerID=c.customerID and abh.abhCashAccId is null and        
 abh.abhCancelled=0 and (datediff(dd,abh.abhBillDate,getdate()) between 0 and 30) and        
 isnull(abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn,0) >0.0        
        
UNION ALL        
        
SELECT         
 abh.abhCompanyid, abhSHopID shopid, abh.abhDepartmentid, abh.abhBillId,        
 abh.abhCustomerid, abh.abhBillDate, abh.abhBillNo, isnull(abh.abhReferenceno,'')         
 Referenceno, abh.abhRemarks, (abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn)        
 as InvAmt ,'31 - 60' as Due, 'RBI' AS Type ,'Trade Debtors' Debtortype,        
 abh.abhUpdateTime, CustomerCategory, abh.abhDueDate duedate,         
 abh.abhDepExRate as depexrate,2304 InterFaceID,         
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName ,c.cusGroupID        
FROM         
 losApartmentBillHeader abh, acustomermaster c        
WHERE         
 abh.abhCustomerID=c.customerID and abh.abhCashAccId is null and        
 abh.abhCancelled=0 and (datediff(dd,abh.abhBillDate,getdate()) between 31 and 60) and        
 isnull(abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn,0) >0.0        
        
UNION ALL        
        
SELECT         
 abh.abhCompanyid, abhSHopID shopid, abh.abhDepartmentid, abh.abhBillId,        
 abh.abhCustomerid, abh.abhBillDate, abh.abhBillNo, isnull(abh.abhReferenceno,'')         
 Referenceno, abh.abhRemarks, (abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn)        
 as InvAmt ,'61 - 90' as Due, 'RBI' AS Type ,'Trade Debtors' Debtortype,        
 abh.abhUpdateTime, CustomerCategory, abh.abhDueDate duedate,         
 abh.abhDepExRate as depexrate,2304 InterFaceID,         
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice ,CustGroupName ,c.cusGroupID       
FROM         
 losApartmentBillHeader abh, acustomermaster c        
WHERE         
 abh.abhCustomerID=c.customerID and abh.abhCashAccId is null and        
 abh.abhCancelled=0 and (datediff(dd,abh.abhBillDate,getdate()) between 61 and 90) and        
 isnull(abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn,0) >0.0        
        
UNION ALL        
        
SELECT         
 abh.abhCompanyid, abhSHopID shopid, abh.abhDepartmentid, abh.abhBillId,        
 abh.abhCustomerid, abh.abhBillDate, abh.abhBillNo, isnull(abh.abhReferenceno,'')         
 Referenceno, abh.abhRemarks, (abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn)        
 as InvAmt ,'> 90' as Due, 'RBI' AS Type ,'Trade Debtors' Debtortype,        
 abh.abhUpdateTime, CustomerCategory, abh.abhDueDate duedate,         
 abh.abhDepExRate as depexrate,2304 InterFaceID,         
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName  ,c.cusGroupID       
FROM         
 losApartmentBillHeader abh, acustomermaster c        
WHERE         
 abh.abhCustomerID=c.customerID and abh.abhCashAccId is null and        
 abh.abhCancelled=0 and (datediff(dd,abh.abhBillDate,getdate())) > 90 and        
 isnull(abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn,0) >0.0        
        
UNION ALL        
--Utility Billing for Manaam        
SELECT         
 tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhDepartmentid, tbh.tbhBillId,        
 tbh.tbhCustomerid, tbh.tbhBillDate, tbh.tbhBillNo, isnull(tbh.tbhReferenceno,'')         
 Referenceno, tbh.tbhRemarks, isnull(tbh.tbhAmount,0)        
 as InvAmt ,'0 - 30' as Due, 'UTB' AS Type ,'Trade Debtors' Debtortype,        
 tbh.tbhUpdateTime, CustomerCategory, tbh.tbhDueDate duedate,         
        
 tbh.tbhDepExRate as depexrate,2305 InterFaceID,         
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice ,CustGroupName  ,c.cusGroupID      
FROM         
 losTenantServiceBillHeader tbh, acustomermaster c        
WHERE         
 tbh.tbhCustomerID=c.customerID and tbh.tbhBankCashID is null and        
 tbh.tbhCancelled=0 and (datediff(dd,tbh.tbhBillDate,getdate()) between 0 and 30) and        
 isnull(tbh.tbhAmount,0) >0.0        
        
UNION ALL        
        
SELECT         
 tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhDepartmentid, tbh.tbhBillId,        
 tbh.tbhCustomerid, tbh.tbhBillDate, tbh.tbhBillNo, isnull(tbh.tbhReferenceno,'')         
 Referenceno, tbh.tbhRemarks, isnull(tbh.tbhAmount,0)        
 as InvAmt ,'31 - 60' as Due, 'UTB' AS Type ,'Trade Debtors' Debtortype,        
 tbh.tbhUpdateTime, CustomerCategory, tbh.tbhDueDate duedate,         
 tbh.tbhDepExRate as depexrate,2305 InterFaceID,         
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName ,c.cusGroupID        
FROM         
 losTenantServiceBillHeader tbh, acustomermaster c        
WHERE         
 tbh.tbhCustomerID=c.customerID and tbh.tbhBankCashID is null and        
 tbh.tbhCancelled=0 and (datediff(dd,tbh.tbhBillDate,getdate()) between 31 and 60) and        
 isnull(tbh.tbhAmount,0) >0.0        
        
UNION ALL        
        
SELECT         
 tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhDepartmentid, tbh.tbhBillId,        
 tbh.tbhCustomerid, tbh.tbhBillDate, tbh.tbhBillNo, isnull(tbh.tbhReferenceno,'')         
 Referenceno, tbh.tbhRemarks, isnull(tbh.tbhAmount,0)        
 as InvAmt ,'61 - 90' as Due, 'UTB' AS Type ,'Trade Debtors' Debtortype,        
 tbh.tbhUpdateTime, CustomerCategory, tbh.tbhDueDate duedate,         
 tbh.tbhDepExRate as depexrate,2305 InterFaceID,         
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName ,c.cusGroupID       
FROM         
 losTenantServiceBillHeader tbh, acustomermaster c        
WHERE         
 tbh.tbhCustomerID=c.customerID and tbh.tbhBankCashID is null and        
 tbh.tbhCancelled=0 and (datediff(dd,tbh.tbhBillDate,getdate()) between 61 and 90) and        
 isnull(tbh.tbhAmount,0)>0.0        
        
UNION ALL        
        
SELECT         
 tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhDepartmentid, tbh.tbhBillId,        
 tbh.tbhCustomerid, tbh.tbhBillDate, tbh.tbhBillNo, isnull(tbh.tbhReferenceno,'')         
 Referenceno, tbh.tbhRemarks, isnull(tbh.tbhAmount,0)        
 as InvAmt ,'> 90' as Due, 'UTB' AS Type ,'Trade Debtors' Debtortype,        
 tbh.tbhUpdateTime, CustomerCategory, tbh.tbhDueDate duedate,         
 tbh.tbhDepExRate as depexrate,2305 InterFaceID,         
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName ,c.cusGroupID      
FROM         
 losTenantServiceBillHeader tbh, acustomermaster c        
WHERE         
 tbh.tbhCustomerID=c.customerID and tbh.tbhBankCashID is null and        
 tbh.tbhCancelled=0 and (datediff(dd,tbh.tbhBillDate,getdate())) > 90 and        
 isnull(tbh.tbhAmount,0) >0.0
GO        
        
--************************************************************************
--************************************************************************
if exists( select * from sysobjects where id = object_id('dbo.vw_Report_service_SupplierLedger'))
	begin
		drop view vw_Report_service_SupplierLedger
	end
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)      
-------------------------------------------------------------------------------------      
CREATE view vw_Report_service_SupplierLedger AS      
      
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       
      
-- account bills      
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 + IsNull(pbhLcAmount, 0)) as billamt, 0.0 as pmtamt,       
 pbhDueDateforPayment duedate, datediff(dd,b.pbhbilldate,getdate()) age,       
 b.updatetime, vw.setdate,      
 convert(numeric(18,2),((b.pbhbillamount + IsNull(pbhLcAmount, 0)) * b.pbhExchangeRate)) cbillamt,       
 0.0 cpmtamt, pbhFinancialID,      
 convert(numeric(18,2),((b.pbhbillamount + IsNull(pbhLcAmount, 0)) * 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      
      
--HQ purchase bills      
--      
union all      
--      
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, 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,       
 0.0 cpmtamt, lphFinancialID,      
 convert(numeric(18,2), ((lphbillamount- isnull(lphdiscount,0)) * 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   --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'      
--      
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      
--      
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      
--      
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'      
      
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      
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
GO
      
      
--************************************************************************
--************************************************************************
if exists( select * from sysobjects where id = object_id('dbo.vwServiceDetailsForCommision'))
	begin
		drop view vwServiceDetailsForCommision
	end
GO
--Created By : Hariharan     
--Created Date : 17/03/2004    
--Altered by Sreejith on 27/05/2010  
--Added the fields v.currencysymbol ,v.serinvhcmpexrate  
--added the case condition for settleddate and settld amt  
Create view dbo.vwServiceDetailsForCommision as    
Select SerInvNo, SerInvHDate, spername, Rate, Qty, (Rate * Qty) Amount,Description,     
SerInvHItemName, case v.serinvhCashInv when 1 then SerInvHDate else settleddate end settleddate,   
amount invamt, case v.serinvhCashInv when 1 then Amount else isnull(settledamt,0.00) end settledamt,   
serinvdType, v.Type,v.ShopId,v.CustomerName,v.currencysymbol ,v.serinvhcmpexrate,v.serinvhCashInv  
 from vwInvoiceServicePartsForPrinting v left Outer Join     
vwSettlements s on v.InvoiceId = s.InvoiceId and v.serinvhCustomerId = s.CustomerId and     
v.ShopId = s.ShopId and 'sbi' = s.Type     
where (Rate * Qty)>0 AND SERINVHCANCELLED =0
GO
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionWithMarginGSTSeparately')
   DROP view dbo.vwDailySalesCollectionWithMarginGSTSeparately
GO


--Modified on           : 04/09/2004                  
--Modified by           : Hariharan                   
--Comments              : Added LOsAccountsInvoiceHeader                  
--   : Added lnvoiceheader - Id grouping                  
--   : included service details of service boooking invoices                    
--   : Corrected join condition of ashops with LOsAccountsInvoiceHeader                  
--   : Corrected the service invoice query to consider the repinvdtype field                
---------------------------------------------------------------------------------------                        
--Modified on                  : 22/11/2010               
--Modified by                  : Nidheesh P V                
--Comments                     : AddedF&B               
---------------------------------------------------------------------------------------                        
--RefNo        : RefNo-2        
--Modified by  : Bijesh.B        
--Date         : 16/06/2011, 21/06/2011        
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)        
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-3        
--Modified by  : Nidheesh P V       
--Date         : 16/06/2011        
--Comments     : Used -costprice instead of costprice       
--Modified Area: Daily Sales Report      
----------------------------------------------------------------------------------------------            
--RefNo        : RefNo-4      
--Modified by  : Bijesh.B      
--Date         : 29/07/2011      
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong      
--             : since, Special invoice return after desp, reqqty is negative,      
--     -1 is multiplied with reqqty      
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-5        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 19/01/2012  
--Comments     : Modified F&B part.  
----------------------------------------------------------------------------------------------         
----------------------------------------------------------------------------------------------         
--Created by   : Bijesh.B   
--Date         : 29/03/2012  
--Ticket id    : JDJ-400367 (new report (rptdailysalescollectionGSTSeparately) for sonee - GST separation)  
--Comments     : Created new view and report (Copy of vwDailySalesCollectionWithMargin)  
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-6        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 26/06/2012  
--Comments     : Exchage rate multiplication problem in POS  
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B    
--Date         : 07/07/2012  
--Comments     : Corrected Margin value for credit invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-7 
--Date         : 09/07/2012  
--Comments     : Corrected Margin value for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-8 
--Date         : 09/07/2012  
--Comments     : Corrected gst amount for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-9
--Date         : 30/07/2012  
--Comments     : Included Other Charges Service Tax in Credit Invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-10
--Date         : 11/08/2012  
--Comments     : Wrong tax amt is showing if same item with different packing type
--               is retuned in GRN
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-10
--Date         : 13/08/2012  
--Comments     : Corrected cost values in GRN in case if return 1 qty out of 2
----------------------------------------------------------------------------------------------       

create VIEW [dbo].[vwDailySalesCollectionWithMarginGSTSeparately] AS                  
Select                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.poshbilldate, convert(numeric(18,8),sum(cashsales)) cashsales,                  
 convert(numeric(18,8),sum(dcashsales)) dcashsales,                   
 convert(numeric(18,8),sum(ccashsales)) ccashsales,                  
 convert(numeric(18,8),sum(creditsales)) creditsales,                  
 convert(numeric(18,8),sum(dcreditsales)) dcreditsales,                   
 convert(numeric(18,8),sum(ccreditsales)) ccreditsales,                   
 convert(numeric(18,8),sum(costvalue)) costvalue,                  
 convert(numeric(18,8),sum(dcostvalue)) dcostvalue,                   
 convert(numeric(18,8),sum(ccostvalue)) ccostvalue,                   
 convert(numeric(18,8),sum(margin)) margin,                  
 convert(numeric(18,8),sum(dmargin)) dmargin, 
 convert(numeric(18,8),sum(cmargin)) cmargin,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid        
 --RefNo-2 start -------------------------        
,convert(numeric(18,8),sum(PdChequeSales)) PdChequeSales,        
convert(numeric(18,8),sum(dPdChequeSales)) dPdChequeSales,        
convert(numeric(18,8),sum(cPdChequeSales)) cPdChequeSales,        
--RefNo-2 ends -------------------------        
convert(numeric(18,8),sum(GSTAmount))GSTAmount,  
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,  
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount  
from                   
 (                  
  select                   
   shopname, poshShopID, poshbilldate,   
   --convert(numeric(18,8),sum(posdunitprice )) cashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)) ccashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dcashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8),sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -  
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))))
	 - sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -  
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   departmentname, poshdepartmentid  departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d                   
  where                   
   poshBillid=posdBillid and poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=0 --RefNo-2  if No PD Cheque Amt involved                       
  group by                   
   shopname, departmentname, poshdepartmentid, poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,poshBillid                  
        
--RefNo-2 Start --------------------------------------------        
--CASH + PD CHEQUE -> Taking only cash amount        
union all        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   --convert(numeric(18,8), 
   --sum(posdunitprice )) cashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshdepexrate)) dcashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshexchangerate)) ccashsales,        
     
   --convert(numeric(18,8),sum(posdunitprice)-pdCheque.PosBankAmount) cashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) dcashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) ccashsales,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8), sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -   
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))))) -   
        sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshdepexrate)) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -   
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
            
   departmentname, poshdepartmentid  departmentid                  
   --,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dPdChequeSales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) cPdChequeSales  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved        
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                            
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
  
/*        
union all        
--CASH + PD CHEQUE -> Taking only Cheque amount        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,        
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales,      
   /*      
   sum(posdcostprice * posdquantity) costvalue,                   
         
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
        
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
        
   (convert(numeric(18,8), sum(posdunitprice ))) -                   
   sum(posdcostprice*posdquantity) margin,      
         
   (convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -   
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin,       
         
   (convert(numeric(18,8), sum(posdunitprice * poshexchangerate))) -       
   sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   */      
   0.0 costvalue,0.0 dcostvalue,0.0 ccostvalue,       
   0.0 margin,0.0 dmargin,0.0 cmargin,        
   departmentname, poshdepartmentid  departmentid,                  
    pdCheque.PosBankAmount as PdChequeSales,        
   (pdCheque.PosBankAmount * poshdepexrate) as  dPdChequeSales,        
   (pdCheque.PosBankAmount * poshexchangerate) as cPdChequeSales        
  from                
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved          
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                          
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
--RefNo-2 ends --------------------------------------------        
*/                  
 union all                  

--RefNo-9 start commented and added                    
  --select                   
  -- shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
  -- --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
  -- --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
  -- --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
  -- convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,             
  -- convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,             
  -- convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,             
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -       
  -- --sum(isnull(idcostprice*idquantity,0)))) margin,                   
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
  -- --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
  -- --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -             
		-- sum(isnull(idcostprice*idquantity,0)))) margin,             
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		-- (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		--   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
  -- departmentname, ihdepartmentid departmentid                   
  -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
  -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
  -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
  -- convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  --from                   
  -- losinvoiceheader  ih                  
  -- left outer join losinvoicedetail invd                  
  -- on ihInvoiceid=idInvoiceid and ihshopid=idshopid     
  -- left outer join                   
  -- (select                  
  --  ioShopID,ioInvoiceID,sum(ioAmount) ioAmount                  
  -- from                  
  --  losInvoiceOC                   
  -- group by                  
  -- ioShopID,ioInvoiceID) ocd                   
  -- on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
  -- ashops s, adepartmentmaster d                   
  --where                   
  -- IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
  -- ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  --group by                   
  -- shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
  -- ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
    
  
   --credit invoice
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) creditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihexchangerate) ccreditsales,             

   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -      
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,  
                    
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) -             
		 sum(isnull(idcostprice*idquantity,0)))) margin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihexchangerate -             
		   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from          
    
     losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid
   
   union all
   
   --Other Charges
   
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   
   convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) creditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate) ccreditsales,             

   0 costvalue,                   
   0 dcostvalue,                  
   0 ccostvalue,                  
                    
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))Margin,            
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))* ihdepexrate  dmargin,             
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))) * ihexchangerate cmargin,  
   
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihexchangerate)cGSTAmount  
  
  from          
     losinvoiceheader  ih                  
   --left outer join losinvoicedetail invd  on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join losInvoiceOC ocd  on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID         
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by  
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid,ocd.ioShopID,ocd.ioInvoiceID
--RefNo-9 ends

 union all                  
                  
  select                   
   shopname, ihShopID, ihinvoicedate,                  
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) Cashsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,         
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,                   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,             
   0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -                   
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -             
		sum(isnull(idcostprice*idquantity,0)))) margin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from                   
   losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join                   
   (select                  
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount        
   from                  
    losInvoiceOC                   
   group by                  
   ioShopID,ioInvoiceID) ocd                   
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
   ashops s, adepartmentmaster d                   
  where                   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=1 and ihdepartmentid = d.departmentid and ihtype ='i'                  
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
                  
 union all                  
   select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehexchangerate)) ccashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
   0.0 creditsales,0.0 dcreditsales , 0.0 ccreditsales , sum(sedcostprice * sedquantity) costvalue,                  
   sum(sedcostprice * sedquantity) * sehdepexrate dcostvalue,                   
   sum(sedcostprice * sedquantity) * sehexchangerate ccostvalue,                  
   --convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedquantity) margin,  
   --convert(numeric(18,8), sum(sedunitprice* sehdepexrate)) -                   
 --sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   --convert(numeric(18,8), sum(sedunitprice * sehexchangerate )) -   
   --sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) - sum(sedcostprice * sedquantity) margin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) -                   
          sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) -   
          sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
    departmentname, sehdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d            
  where          
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange = 'E' and sehshopid = shopid and sehdepartmentid = d.departmentid          
  group by      
   shopname, sehshopid, departmentname, sehdepartmentid, sehexchangedate ,                  
   departmentname,sehdepexrate, sehexchangerate,sehExchangeID                  
 union all                  
       
 -- RefNo-4 start  commented below      
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  sum(idunitprice )) cashsales, convert(numeric(18,8),                   
 ------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,8),                   
 ------  sum(idunitprice * ihexchangerate)) ccashsales,                  
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  (convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                   
 ------  (convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                   
 ------  (convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin, departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  ihdepartmentid =d.departmentid and idratetype=0 and ihproforma=0 and                   
 ------  ihshopid = shopid and ihcashinvoice=1 and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, departmentname, ihdepartmentid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
 ------ union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                   
 ------  0.0 ccashsales, convert(numeric(18,8), sum(idunitprice )) creditsales,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate)) dcreditsales,          
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate)) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                  
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                  
 ------  convert(numeric(18,8), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate) - sum(idcostprice*reqqty) * ihexchangerate) cmargin,                   
 ------  departmentname, ihDepartmentId departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  idratetype=0 and ihproforma=0 and ihshopid = shopid and                   
 ------  ihcashinvoice=0 and ihDepartmentId = d.departmentid                  
 ------  and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname, ihinvoicedate ,                   
 ------  ihexchangerate, ihdepexrate,ihInvoiceid                  
                  
 ------union all                  
 -- RefNo-4 ends      
                  
  select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),-sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehexchangerate)) ccashsales,                  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(-sedcostprice * sedExchangeQty) costvalue,    --RefNo-3              
   sum(-sedcostprice * sedExchangeQty) * sehdepexrate dcostvalue, sum(-sedcostprice * sedExchangeQty)     --RefNo-3             
   * sehexchangerate ccostvalue,  
    ---(convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedExchangeQty)) margin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -                   
   --    sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -   
    --    sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
           sum(sedcostprice * sedExchangeQty)) margin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -                   
        sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
        sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
  
   departmentname, sehdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d                   
  where        
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid                   
   and sehdepartmentid = d.departmentid                   
  group by                   
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,                  
   sehdepexrate,sedExchangeid                  
 union all       
       
 -- RefNo-4 start                  
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  -(sum(idunitprice ))) cashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihexchangerate))) ccashsales,                   
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(idcostprice * abs(reqqty)) costvalue,                   
 ------  sum(idcostprice * abs(reqqty)) * ihdepexrate dcostvalue, sum(idcostprice * abs(reqqty)) *                   
 ------  ihexchangerate ccostvalue,  -((convert(numeric(18,8), sum(idunitprice ))) -            
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0                    
 ------  and ihproforma=0 and ihshopid = shopid and ihTransfinished = 1                   
 ------  and ihcashinvoice=1 AND IDratetype=1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihdepartmentid, departmentname, ihshopid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
          
 ------union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice ))) creditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihdepexrate))) dcreditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihexchangerate))) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                   
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8),                   
 ------  sum(idunitprice ))) -  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND  
 ------  IHCANCELLED = 0 and ihproforma = 0 and ihshopid = shopid and                   
 ------  ihcashinvoice = 0 and idratetype = 1 and ihtransfinished = 1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname,                  
 ------  ihinvoicedate , ihexchangerate, ihdepexrate,ihInvoiceid                  
                  
 ------union all                  
      
-- special Invoice (cash)        
select         
shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccashsales,    
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales,   
  
0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty) margin,             
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,        
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty))* ihexchangerate cmargin,  
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d   
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                    
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all                                      
      
-------- special invoice - return before despatch                          
select shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,       
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-sum(idcostprice * reqqty) costvalue ,      
-sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
-sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
     
union all                                      
                                   
-- Special invoice return  - after desp                  
select shopname,                                     
 ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,     
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                        
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1         
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
-- special Invoice (credit)      
union all      
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccreditsales,    
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
       
 sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,      
--(convert(numeric(18,8), sum(idunitprice)))-sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))))-sum(idcostprice*reqqty) margin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice <>1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all         
      
-- special invoice - return before despatch                          
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,  
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,     
  
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
 -sum(idcostprice * reqqty) costvalue ,      
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) margin,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice <>1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                          
union all                                      
                                   
-- Special invoice return  - after desp                                    
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,  
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate))dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate))ccreditsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)dcreditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)ccreditsales,       
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
--idUnitPrice, idItemTaxAmount  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice <>1                                     
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
 -- RefNo-4 ends       
  union all                 

-- RefNo-10 start commented below and added
  --select                   
  -- shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) creditsales,                   
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                   
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   

  -- -sum(grncostprice*grndquantity) costvalue,
  -- - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                  
  -- -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,                   

  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))))-  
  --         sum(grncostprice*grndquantity)) margin,  
  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -                   
  --     sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -  
  --      sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,
                           
  -- departmentname, grnhdepartmentid departmentid                  
  -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
  -- ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
  -- ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
  --  -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  --from                   
  -- losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d                   
  --where               
  -- GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0                   
  -- and grnhshopid = shopid and grnhdepartmentid = d.departmentid                   
  --group by                   
  -- shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,                   
  -- grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID                  

select                   
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) creditsales,                   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   
   -- -sum(grncostprice*grndquantity) costvalue,
   -- -sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                  
   -- -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,  
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))costvalue,
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))* grnhdepexrate dcostvalue,                  
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))* grnhexchangerate ccostvalue,  

   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))))-  
           sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))) margin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) -                   
       sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity)))* grnhdepexRate dmargin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) -  
        sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))) * grnhExchangeRate cmargin,                   

   departmentname, grnhdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,-convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))GSTAmount  
   ,-convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
    -convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  from losgoodsreturnnoteheader 
   inner join losgoodsreturnnotedetail on  GrnhGoodsreturnnoteID = GRNDReturnNoteID 
		and grnhShopid = GRNDShopid
   inner join ashops s on  grnhshopid = shopid
   inner join adepartmentmaster d  on grnhdepartmentid = d.departmentid                   
   -- below linking with credit invoice was used since
   -- qty based on packing type was not available in GRN table
   left join  losinvoiceheader  ih on ih.ihInvoiceID = losgoodsreturnnoteheader.GrnhInvoiceID
		and ih.ihShopID = losgoodsreturnnoteheader.grnhShopid
   left outer join losinvoicedetail invd on ihInvoiceid=idInvoiceid and ihshopid=idshopid 
		and invd.idPackingTypeID = losgoodsreturnnotedetail.grndPackTypeId
		and invd.idShopID = losgoodsreturnnotedetail.GRNDShopid
  where 
	   GrnhCancel =0                   
  group by                   
		shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,                   
		grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID 

-- RefNo-10 ends

  --hari added to include the service booking invoice parts replaced items                  
 UNION ALL                  
  
  --service invoice (cash)                
  select                   
   shopname, repinvdshopid, serinvhdate,  
   --convert(numeric(18,8),sum(repinvdrate* repinvdqty)) cashsales,  
   --convert(numeric(18,8),sum(repinvdrate* seinvhdepexrate * repinvdqty)) dcashsales,                  
   --convert(numeric(18,8),sum(repinvdrate* serinvhcmpexrate * repinvdqty)) ccashsales,                  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcashsales,            
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccashsales,            

   0.0 creditsales, 0.0 dcreditsales , 0.0 ccreditsales ,  sum(repinvdcostprice * repinvdqty) costvalue,                   
   sum(repinvdcostprice * repinvdqty) * seinvhdepexrate  dcostvalue,                   
   sum(repinvdcostprice * repinvdqty) *serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -  
   --  sum(repinvdcostprice * repinvdqty),                   
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,   
   --convert(numeric(18,8),(sum(repinvdrate  * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty)margin,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate dmargin,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
 -sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate cmargin,          
  
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --RefNo-8  start commneted, since this gst amount is taken care in below
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
 --convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
   ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
--RefNo-8 ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d                   
  where                   
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1                  
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, serinvhDepartmentid,                   
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid                   
                  
 union all                  
 
  --service Details  (cash)                
  select                   
   shopname, serinvhshopid, serinvhdate,  
   --convert(numeric(18,8) , serinvhserviceamt) cashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccashsales ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate)dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate)ccashsales ,             
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                       
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,    
   
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)),             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,       
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) *  serinvhcmpexrate) ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate)dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate)ccashsales ,             

   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount  
  from                   
--RefNo-8 start commented below
   --losserviceinvheader, ashops s, adepartmentmaster d                   
	 --where                   
	 --  serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1         
	 --  and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                  
   
 losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid   and Patindex('%y%',repinvdtype)>0 
 where                   
	serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1  
    and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends 
 union all
  
  --service invoice (credit)	    
    select                   
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , (sum(repinvdrate* repinvdqty))) creditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * seinvhdepexrate * repinvdqty))) dcreditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * serinvhcmpexrate * repinvdqty))) ccreditsales ,   
  
   convert(numeric(18,8),(sum( (repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
                     
   sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*                   
   seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty), convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty) * seinvhdepexrate , convert(numeric(18,8) ,                   
   --( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate ,                   
   
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * seinvhdepexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate,  
   
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  --RefNo-8  start commneted, since this gst amount is taken care in below
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
	 -- convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
	,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
  --RefNo-8  ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader,                   
   ashops s, adepartmentmaster d 
  where 
   serinvhid = repinvinvoiceid and                   
   serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is null                   
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid                    
   and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,                  
   serinvhcmpexrate ,serinvhid   
   
   union all
          
  --service Details   (credit)               
  select                   
 shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , serinvhserviceamt) creditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcreditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccreditsales ,     
   
   --RefNo-8 start commented below
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) creditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate) dcreditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate) ccreditsales ,             
   convert(numeric(18,8),serinvhserviceamt- (isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) creditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
   --RefNo-8 ends
   
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*seinvhdepexrate) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*serinvhcmpexrate) ,             
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount    
  from                   
  --RefNo-8 start commented below
  -- losserviceinvheader, ashops s, adepartmentmaster d                   
  --where                   
  -- serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                   
  losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0 
 where                   
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends
   
  union all                  


  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002                  
  --credit           
  select           
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,                   
   0.0 ccashsales,                  
    convert(numeric(18,8), sum(redunitprice)) creditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehdepexrate)  dcreditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehexchangerate) ccreditsales,
   sum(redcostprice * redquantity) costvalue,                   
   sum(redcostprice * redquantity) * rehdepexrate dcostvalue, 
   sum(redcostprice * redquantity) * rehexchangerate ccostvalue,
   (convert(numeric(18,8), sum(redunitprice ))) -  sum(redcostprice * redquantity) margin,
   (convert(numeric(18,8), sum(redunitprice * rehdepexrate))) -                   
		sum(redcostprice * redquantity) * rehdepexrate dmargin,
   (convert(numeric(18,8), sum(redunitprice * rehexchangerate))) - 
		sum(redcostprice * redquantity) * rehexchangerate cmargin,                   
   departmentname, rehdepartmentid                  
 ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,0,0,0  
  from                   
   losExportDetail, losExportHeader, ashops s, adepartmentmaster d                   
  where                   
   rehExportID = redExportID and rehshopid = redshopid AND                   
   reHCANCELLED=0 and rehtype ='i' and                  
   rehproforma=0 and rehshopid = shopid and rehcashinvoice=0 and                   
   rehdepartmentid = d.departmentid                   
  group by                   
   shopname, rehshopid, departmentname, rehdepartmentid, rehExportDate,                   
   rehdepexrate, rehexchangerate,rehExportID                   
            
 union all                  
 -- added From Vwcashsales -Margin Not calculating                  
                   
 select                   
  s.shopname, vws.sishopid, vws.siinvoicedate,                   
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,                   
  convert(numeric(18,8),sum(vws.sidamount)) as  dcashsales,  -- RefNo-7 corrected amount                  
  convert(numeric(18,8),sum(vws.sicamount)) as ccashsales,   -- RefNo-7 corrected amount                                  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
   0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
  convert(numeric(18,8),sum(vws.siamount))as margin,    -- RefNo-7 included  -vws.GSTAmount                              
  convert(numeric(18,8),sum(vws.sidamount))as  dmargin,    -- RefNo-7 included  -vws.GSTAmount                               
  convert(numeric(18,8),sum(vws.sicamount))as cmargin,  -- RefNo-7 included  -vws.GSTAmount                              
  d.departmentname,lah.aidepartmentid  departmentid                   
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
  , sum(vws.dGSTAmount)as dGSTAmount  
  , sum(vws.cGSTAmount)as cGSTAmount  
 from                   
  vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d ,ashops s                  
 where                   
  aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
  aishopid = sishopid and lah.aicashinvoice=1 and       
  lah.aidepartmentid =d.departmentid and s.departmentid = d.departmentid                  
  and aiShopId = s.ShopId                  
 group by                   
  s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid, vws.siinvoicedate                  
  ,aidepexrate, aiexchangerate               
 union all                  
                  
    select s.shopname, vws.sishopid, vws.siinvoicedate,                   
    0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
    convert(numeric(18,8),sum(vws.siamount))as creditsales,                   
    convert(numeric(18,8),sum(vws.sidamount))as dcreditsales, -- RefNo-7 corrected amount                   
    convert(numeric(18,8),sum(vws.sidamount))as ccreditsales, -- RefNo-7 corrected amount                                    
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
    convert(numeric(18,8),sum(vws.siamount)) as margin,    -- RefNo-7 included  -vws.GSTAmount              
    convert(numeric(18,8),sum(vws.sidamount)) as dmargin,  -- RefNo-7 included  -vws.GSTAmount               
convert(numeric(18,8),sum(vws.sicamount)) as cmargin,  -- RefNo-7 included  -vws.GSTAmount   
    d.departmentname,lah.aidepartmentid  departmentid                   
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
    , sum(vws.dGSTAmount)as dGSTAmount  
    , sum(vws.cGSTAmount)as cGSTAmount  
    from vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d,ashops s      
    where aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
    aishopid = sishopid and lah.aicashinvoice=0 and lah.aidepartmentid =d.departmentid                  
    and s.departmentid = d.departmentid and s.ShopId = aiShopId group by                       
    s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid,vws.siinvoicedate,aiinvoiceid,
    aidepexrate                   
                   
    UniOn All -- added from vwCashSales                 
    --Shop debit credit notes and handling debit notes which are debit to the                
    -- customer and hence act as invoices to be settled                      
    Select  s.shopname,losdcnshopid,losdcndate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
    COnvert(numeric(18,8),Sum(losDCNAmount))  creditsales,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dcreditsales,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  ccreditsales,               
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    COnvert(numeric(18,8),Sum(losDCNAmount))  margin,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dmargin,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  cmargin,              
 d.departmentname,losdcndepartmentid                   
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2    
       ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount      
    From Ashops s,  losdebitcreditnote, adepartmentmaster d               
    Where  s.shopid = losdcnshopid And s.accountable Is Not Null                   
    And d.DepartmentID = losdcndepartmentid And losdcncancelled =0                    
    And losdcndebit =1  Group By s.shopname,d.departmentname,losdcnshopid,                  
    losdcndate, losdepexrate, losexchangerate,losdcndepartmentid              
              
    --hq serivce invoice dOne for shop                    
    Union all              
               
    Select  null, 0,ai.invoicedate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  creditsales,             
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dcreditsales,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  ccreditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)ccreditsales,         
  
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  margin,                     
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dmargin,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  cmargin,   
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)) * exchangerate)cmargin,        
                 
    d.departmentname,ai.departmentid           
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
     ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount   
     ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,  
      convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount  
  
  From accountsinvoiceheader ai, serviceinvoicedetails ser ,adepartmentmaster d              
    Where ai.invoiceid = ser.invoiceid And ai.companyid =                     
    ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0             
    and ai.departmentid = d.departmentid and ai.companyid = d.companyid               
    Group By  ai.invoicedate,depexrate,exchangerate,              
    d.departmentname,ai.departmentid              
        
  
 ----F&B---------------------------   
 --RefNo-5----------------------------------------------start----------------------------------------------------------------------------  
 ----------------------------------------  
 -- select v.* from        
 --(        
--select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales,       
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 --inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 --UNION ALL        
        
 --select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales,        
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,   
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 --inner join aitem a on a.itemid=fb_pd_dishid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 --where fb_pd_AddedItemtype=2        
 --)v       
  
/*  
union all  
  select shopname,poshShopID,poshBillDate,Cashsales,DepCashsales,ComCashsales,Creditsales,DepCreditsales,  
 ComCreditsales,costprice,dcostprice,ccostprice,margin,dmargin,cmargin,deptname,deptid,  
PdChequeSales,dPdChequeSales,cPdChequeSales  from  
 (        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid) costprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2        
  fb_pd_processdetailid  
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 UNION ALL        
        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2   
  fb_pd_processdetailid       
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 inner join aitem a on a.itemid=fb_pd_dishid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 where fb_pd_AddedItemtype=2        
  
  
 )  
  
  v        
 --RefNo-5----------------------------------------------end----------------------------------------------------------------------------  
  ----------------------------------------                  
  */  
     
 )cashcreditcollection      
group by                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid,                   
 cashcreditcollection.poshbilldate   
  

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

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionWithMarginGSTSeparately')
   DROP view dbo.vwDailySalesCollectionWithMarginGSTSeparately
GO


--Modified on           : 04/09/2004                  
--Modified by           : Hariharan                   
--Comments              : Added LOsAccountsInvoiceHeader                  
--   : Added lnvoiceheader - Id grouping                  
--   : included service details of service boooking invoices                    
--   : Corrected join condition of ashops with LOsAccountsInvoiceHeader                  
--   : Corrected the service invoice query to consider the repinvdtype field                
---------------------------------------------------------------------------------------                        
--Modified on                  : 22/11/2010               
--Modified by                  : Nidheesh P V                
--Comments                     : AddedF&B               
---------------------------------------------------------------------------------------                        
--RefNo        : RefNo-2        
--Modified by  : Bijesh.B        
--Date         : 16/06/2011, 21/06/2011        
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)        
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-3        
--Modified by  : Nidheesh P V       
--Date         : 16/06/2011        
--Comments     : Used -costprice instead of costprice       
--Modified Area: Daily Sales Report      
----------------------------------------------------------------------------------------------            
--RefNo        : RefNo-4      
--Modified by  : Bijesh.B      
--Date         : 29/07/2011      
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong      
--             : since, Special invoice return after desp, reqqty is negative,      
--     -1 is multiplied with reqqty      
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-5        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 19/01/2012  
--Comments     : Modified F&B part.  
----------------------------------------------------------------------------------------------         
----------------------------------------------------------------------------------------------         
--Created by   : Bijesh.B   
--Date         : 29/03/2012  
--Ticket id    : JDJ-400367 (new report (rptdailysalescollectionGSTSeparately) for sonee - GST separation)  
--Comments     : Created new view and report (Copy of vwDailySalesCollectionWithMargin)  
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-6        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 26/06/2012  
--Comments     : Exchage rate multiplication problem in POS  
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B    
--Date         : 07/07/2012  
--Comments     : Corrected Margin value for credit invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-7 
--Date         : 09/07/2012  
--Comments     : Corrected Margin value for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-8 
--Date         : 09/07/2012  
--Comments     : Corrected gst amount for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-9
--Date         : 30/07/2012  
--Comments     : Included Other Charges Service Tax in Credit Invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-10
--Date         : 11/08/2012  
--Comments     : Wrong tax amt is showing if same item with different packing type
--               is retuned in GRN
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-10
--Date         : 13/08/2012  
--Comments     : Corrected cost values in GRN in case if return 1 qty out of 2
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-11
--Date         : 16/08/2012  
--Comments     : Corrected credit sales values in case of two items having same type and one
--               normal item with 2 quantities each, and returning only 1 qty in grn.
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-12
--Date         : 17/08/2012  
--Comments     : Corrected credit sales values in case while deleting GRN.
----------------------------------------------------------------------------------------------       

CREATE VIEW [dbo].[vwDailySalesCollectionWithMarginGSTSeparately] AS                  
Select                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.poshbilldate, convert(numeric(18,8),sum(cashsales)) cashsales,                  
 convert(numeric(18,8),sum(dcashsales)) dcashsales,                   
 convert(numeric(18,8),sum(ccashsales)) ccashsales,                  
 convert(numeric(18,8),sum(creditsales)) creditsales,                  
 convert(numeric(18,8),sum(dcreditsales)) dcreditsales,                   
 convert(numeric(18,8),sum(ccreditsales)) ccreditsales,                   
 convert(numeric(18,8),sum(costvalue)) costvalue,                  
 convert(numeric(18,8),sum(dcostvalue)) dcostvalue,                   
 convert(numeric(18,8),sum(ccostvalue)) ccostvalue,                   
 convert(numeric(18,8),sum(margin)) margin,                  
 convert(numeric(18,8),sum(dmargin)) dmargin, 
 convert(numeric(18,8),sum(cmargin)) cmargin,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid        
 --RefNo-2 start -------------------------        
,convert(numeric(18,8),sum(PdChequeSales)) PdChequeSales,        
convert(numeric(18,8),sum(dPdChequeSales)) dPdChequeSales,        
convert(numeric(18,8),sum(cPdChequeSales)) cPdChequeSales,        
--RefNo-2 ends -------------------------        
convert(numeric(18,8),sum(GSTAmount))GSTAmount,  
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,  
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount  
from                   
 (                  
  select                   
   shopname, poshShopID, poshbilldate,   
   --convert(numeric(18,8),sum(posdunitprice )) cashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)) ccashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dcashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8),sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -  
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))))
	 - sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -  
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   departmentname, poshdepartmentid  departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d                   
  where                   
   poshBillid=posdBillid and poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=0 --RefNo-2  if No PD Cheque Amt involved                       
  group by                   
   shopname, departmentname, poshdepartmentid, poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,poshBillid                  
        
--RefNo-2 Start --------------------------------------------        
--CASH + PD CHEQUE -> Taking only cash amount        
union all        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   --convert(numeric(18,8), 
   --sum(posdunitprice )) cashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshdepexrate)) dcashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshexchangerate)) ccashsales,        
     
   --convert(numeric(18,8),sum(posdunitprice)-pdCheque.PosBankAmount) cashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) dcashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) ccashsales,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8), sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -   
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))))) -   
        sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshdepexrate)) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -   
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
            
   departmentname, poshdepartmentid  departmentid                  
   --,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dPdChequeSales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) cPdChequeSales  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved        
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                            
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
  
/*        
union all        
--CASH + PD CHEQUE -> Taking only Cheque amount        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,        
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales,      
   /*      
   sum(posdcostprice * posdquantity) costvalue,                   
         
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
        
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
        
   (convert(numeric(18,8), sum(posdunitprice ))) -                   
   sum(posdcostprice*posdquantity) margin,      
         
   (convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -   
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin,       
         
   (convert(numeric(18,8), sum(posdunitprice * poshexchangerate))) -       
   sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   */      
   0.0 costvalue,0.0 dcostvalue,0.0 ccostvalue,       
   0.0 margin,0.0 dmargin,0.0 cmargin,        
   departmentname, poshdepartmentid  departmentid,                  
    pdCheque.PosBankAmount as PdChequeSales,        
   (pdCheque.PosBankAmount * poshdepexrate) as  dPdChequeSales,        
   (pdCheque.PosBankAmount * poshexchangerate) as cPdChequeSales        
  from                
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved          
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                          
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
--RefNo-2 ends --------------------------------------------        
*/                  
 union all                  

--RefNo-9 start commented and added                    
  --select                   
  -- shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
  -- --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
  -- --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
  -- --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
  -- convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,             
  -- convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,             
  -- convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,             
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -       
  -- --sum(isnull(idcostprice*idquantity,0)))) margin,                   
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
  -- --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
  -- --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -             
		-- sum(isnull(idcostprice*idquantity,0)))) margin,             
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		-- (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		--   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
  -- departmentname, ihdepartmentid departmentid                   
  -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
  -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
  -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
  -- convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  --from                   
  -- losinvoiceheader  ih                  
  -- left outer join losinvoicedetail invd                  
  -- on ihInvoiceid=idInvoiceid and ihshopid=idshopid     
  -- left outer join                   
  -- (select                  
  --  ioShopID,ioInvoiceID,sum(ioAmount) ioAmount                  
  -- from                  
  --  losInvoiceOC                   
  -- group by                  
  -- ioShopID,ioInvoiceID) ocd                   
  -- on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
  -- ashops s, adepartmentmaster d                   
  --where                   
  -- IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
  -- ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  --group by                   
  -- shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
  -- ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
    
  
   --credit invoice
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) creditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihexchangerate) ccreditsales,             

   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -      
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,  
                    
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) -             
		 sum(isnull(idcostprice*idquantity,0)))) margin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihexchangerate -             
		   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from          
    
     losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid
   
   union all
   
   --Other Charges
   
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   
   convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) creditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate) ccreditsales,             

   0 costvalue,                   
   0 dcostvalue,                  
   0 ccostvalue,                  
                    
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))Margin,            
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))* ihdepexrate  dmargin,             
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))) * ihexchangerate cmargin,  
   
 departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihexchangerate)cGSTAmount  
  
  from          
     losinvoiceheader  ih                  
   --left outer join losinvoicedetail invd  on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join losInvoiceOC ocd  on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID         
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by  
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid,ocd.ioShopID,ocd.ioInvoiceID
--RefNo-9 ends

 union all                  
                  
  select                   
   shopname, ihShopID, ihinvoicedate,                  
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) Cashsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,         
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,                   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,             
   0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -                   
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -             
		sum(isnull(idcostprice*idquantity,0)))) margin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from                   
   losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join                   
   (select                  
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount        
   from                  
    losInvoiceOC                   
   group by                  
   ioShopID,ioInvoiceID) ocd                   
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
   ashops s, adepartmentmaster d                   
  where                   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=1 and ihdepartmentid = d.departmentid and ihtype ='i'                  
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
                  
 union all                  
   select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehexchangerate)) ccashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
   0.0 creditsales,0.0 dcreditsales , 0.0 ccreditsales , sum(sedcostprice * sedquantity) costvalue,                  
   sum(sedcostprice * sedquantity) * sehdepexrate dcostvalue,                   
   sum(sedcostprice * sedquantity) * sehexchangerate ccostvalue,                  
   --convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedquantity) margin,  
   --convert(numeric(18,8), sum(sedunitprice* sehdepexrate)) -                   
 --sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   --convert(numeric(18,8), sum(sedunitprice * sehexchangerate )) -   
   --sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) - sum(sedcostprice * sedquantity) margin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) -                   
          sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) -   
          sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
    departmentname, sehdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d            
  where          
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange = 'E' and sehshopid = shopid and sehdepartmentid = d.departmentid          
  group by      
   shopname, sehshopid, departmentname, sehdepartmentid, sehexchangedate ,                  
   departmentname,sehdepexrate, sehexchangerate,sehExchangeID                  
 union all                  
       
 -- RefNo-4 start  commented below      
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  sum(idunitprice )) cashsales, convert(numeric(18,8),                   
 ------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,8),                   
 ------  sum(idunitprice * ihexchangerate)) ccashsales,                  
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  (convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                   
 ------  (convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                   
 ------  (convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin, departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  ihdepartmentid =d.departmentid and idratetype=0 and ihproforma=0 and                   
 ------  ihshopid = shopid and ihcashinvoice=1 and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, departmentname, ihdepartmentid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
 ------ union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                   
 ------  0.0 ccashsales, convert(numeric(18,8), sum(idunitprice )) creditsales,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate)) dcreditsales,          
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate)) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                  
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                  
 ------  convert(numeric(18,8), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate) - sum(idcostprice*reqqty) * ihexchangerate) cmargin,                   
 ------  departmentname, ihDepartmentId departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  idratetype=0 and ihproforma=0 and ihshopid = shopid and                   
 ------  ihcashinvoice=0 and ihDepartmentId = d.departmentid                  
 ------  and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname, ihinvoicedate ,                   
 ------  ihexchangerate, ihdepexrate,ihInvoiceid   
                  
 ------union all                  
 -- RefNo-4 ends      
                  
  select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),-sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehexchangerate)) ccashsales,                  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(-sedcostprice * sedExchangeQty) costvalue,    --RefNo-3              
   sum(-sedcostprice * sedExchangeQty) * sehdepexrate dcostvalue, sum(-sedcostprice * sedExchangeQty)     --RefNo-3             
   * sehexchangerate ccostvalue,  
    ---(convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedExchangeQty)) margin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -                   
   --    sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -   
    --    sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
           sum(sedcostprice * sedExchangeQty)) margin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -                   
        sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
        sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
  
   departmentname, sehdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d                   
  where        
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid                   
   and sehdepartmentid = d.departmentid                   
  group by                   
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,                  
   sehdepexrate,sedExchangeid                  
 union all       
       
 -- RefNo-4 start                  
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  -(sum(idunitprice ))) cashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihexchangerate))) ccashsales,                   
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(idcostprice * abs(reqqty)) costvalue,                   
 ------  sum(idcostprice * abs(reqqty)) * ihdepexrate dcostvalue, sum(idcostprice * abs(reqqty)) *                   
 ------  ihexchangerate ccostvalue,  -((convert(numeric(18,8), sum(idunitprice ))) -            
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0                    
 ------  and ihproforma=0 and ihshopid = shopid and ihTransfinished = 1                   
 ------  and ihcashinvoice=1 AND IDratetype=1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihdepartmentid, departmentname, ihshopid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
          
 ------union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice ))) creditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihdepexrate))) dcreditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihexchangerate))) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                   
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8),                   
 ------  sum(idunitprice ))) -  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND  
 ------  IHCANCELLED = 0 and ihproforma = 0 and ihshopid = shopid and                   
 ------  ihcashinvoice = 0 and idratetype = 1 and ihtransfinished = 1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname,                  
 ------  ihinvoicedate , ihexchangerate, ihdepexrate,ihInvoiceid                  
                  
 ------union all                  
      
-- special Invoice (cash)        
select         
shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccashsales,    
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales,   
  
0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty) margin,             
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,        
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty))* ihexchangerate cmargin,  
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d   
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                    
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all                                      
      
-------- special invoice - return before despatch                          
select shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,       
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-sum(idcostprice * reqqty) costvalue ,      
-sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
-sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
     
union all                                      
                                   
-- Special invoice return  - after desp                  
select shopname,                                     
 ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,     
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                        
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1         
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
-- special Invoice (credit)      
union all      
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccreditsales,    
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
       
 sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,      
--(convert(numeric(18,8), sum(idunitprice)))-sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))))-sum(idcostprice*reqqty) margin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice <>1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all         
      
-- special invoice - return before despatch                          
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,  
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,     
  
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
 -sum(idcostprice * reqqty) costvalue ,      
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) margin,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice <>1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                          
union all                                      
                                   
-- Special invoice return  - after desp                                    
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,  
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate))dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate))ccreditsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)dcreditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)ccreditsales,       
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
--idUnitPrice, idItemTaxAmount  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice <>1                                     
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
 -- RefNo-4 ends       
  union all                 

-- RefNo-10 start commented below and added
  --select                   
  -- shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) creditsales,                   
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                   
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   

  -- -sum(grncostprice*grndquantity) costvalue,
  -- - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                  
  -- -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,                   

  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))))-  
  --         sum(grncostprice*grndquantity)) margin,  
  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -                   
  --     sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -  
  --      sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,
                           
  -- departmentname, grnhdepartmentid departmentid                  
  -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
  -- ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
  -- ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
  --  -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  --from                   
  -- losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d                   
  --where               
  -- GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0                   
  -- and grnhshopid = shopid and grnhdepartmentid = d.departmentid                   
  --group by                   
  -- shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,                   
  -- grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID                  

select                   
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) creditsales,                   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                 
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   
   -- -sum(grncostprice*grndquantity) costvalue,
   -- -sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                  
   -- -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,  
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))costvalue,
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))* grnhdepexrate dcostvalue,                  
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))* grnhexchangerate ccostvalue,  

   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))))-  
           sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))) margin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) -                   
       sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity)))* grnhdepexRate dmargin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) -  
        sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))) * grnhExchangeRate cmargin,                   

   departmentname, grnhdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,-convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))GSTAmount  
   ,-convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
    -convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  from losgoodsreturnnoteheader 
   inner join losgoodsreturnnotedetail on  GrnhGoodsreturnnoteID = GRNDReturnNoteID 
		and grnhShopid = GRNDShopid
   inner join ashops s on  grnhshopid = shopid
   inner join adepartmentmaster d  on grnhdepartmentid = d.departmentid                   
   -- below linking with credit invoice was used since
   -- qty based on packing type was not available in GRN table
   left join  losinvoiceheader  ih on ih.ihInvoiceID = losgoodsreturnnoteheader.GrnhInvoiceID
		and ih.ihShopID = losgoodsreturnnoteheader.grnhShopid 
		and IHCANCELLED=0 and ihproforma=0 and ihshopid = s.shopid and    --RefNo-12 added                  
		ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'   --RefNo-12 added
		
   left outer join losinvoicedetail invd on ihInvoiceid=idInvoiceid and ihshopid=idshopid 
		and invd.idItemID = losgoodsreturnnotedetail.GRNDItemID --RefNo-11
		and invd.idPackingTypeID = losgoodsreturnnotedetail.grndPackTypeId
		and invd.idShopID = losgoodsreturnnotedetail.GRNDShopid
  where 
	   GrnhCancel =0                   
  group by                   
		shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,                   
		grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID 

-- RefNo-10 ends

  --hari added to include the service booking invoice parts replaced items                  
 UNION ALL                  
  
  --service invoice (cash)                
  select                   
   shopname, repinvdshopid, serinvhdate,  
   --convert(numeric(18,8),sum(repinvdrate* repinvdqty)) cashsales,  
   --convert(numeric(18,8),sum(repinvdrate* seinvhdepexrate * repinvdqty)) dcashsales,                  
   --convert(numeric(18,8),sum(repinvdrate* serinvhcmpexrate * repinvdqty)) ccashsales,                  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcashsales,            
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccashsales,            

   0.0 creditsales, 0.0 dcreditsales , 0.0 ccreditsales ,  sum(repinvdcostprice * repinvdqty) costvalue,                   
   sum(repinvdcostprice * repinvdqty) * seinvhdepexrate  dcostvalue,  
   sum(repinvdcostprice * repinvdqty) *serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -  
   --  sum(repinvdcostprice * repinvdqty),                   
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,   
   --convert(numeric(18,8),(sum(repinvdrate  * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty)margin,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate dmargin,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
 -sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate cmargin,          
  
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --RefNo-8  start commneted, since this gst amount is taken care in below
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
 --convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
   ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
--RefNo-8 ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d                   
  where                   
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1                  
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, serinvhDepartmentid,                   
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid                   
                  
 union all                  
 
  --service Details  (cash)                
  select                   
   shopname, serinvhshopid, serinvhdate,  
   --convert(numeric(18,8) , serinvhserviceamt) cashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccashsales ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate)dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate)ccashsales ,             
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                       
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,    
   
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)),          
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,       
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) *  serinvhcmpexrate) ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate)dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate)ccashsales ,             

   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount  
  from                   
--RefNo-8 start commented below
   --losserviceinvheader, ashops s, adepartmentmaster d                   
	 --where                   
	 --  serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1         
	 --  and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                  
   
 losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid   and Patindex('%y%',repinvdtype)>0 
 where                   
	serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1  
    and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends 
 union all
  
  --service invoice (credit)	    
    select                   
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , (sum(repinvdrate* repinvdqty))) creditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * seinvhdepexrate * repinvdqty))) dcreditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * serinvhcmpexrate * repinvdqty))) ccreditsales ,   
  
   convert(numeric(18,8),(sum( (repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
                     
   sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*                   
   seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty), convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty) * seinvhdepexrate , convert(numeric(18,8) ,                   
   --( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate ,                   
   
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * seinvhdepexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate,  

   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  --RefNo-8  start commneted, since this gst amount is taken care in below
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
	 -- convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
	,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
  --RefNo-8  ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader,                   
   ashops s, adepartmentmaster d 
  where 
   serinvhid = repinvinvoiceid and                   
   serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is null                   
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid                    
   and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,                  
   serinvhcmpexrate ,serinvhid   
   
   union all
          
  --service Details   (credit)               
  select                   
 shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , serinvhserviceamt) creditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcreditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccreditsales ,     
   
   --RefNo-8 start commented below
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) creditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate) dcreditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate) ccreditsales ,             
   convert(numeric(18,8),serinvhserviceamt- (isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) creditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
   --RefNo-8 ends
   
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*seinvhdepexrate) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*serinvhcmpexrate) ,             
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount    
  from                   
  --RefNo-8 start commented below
  -- losserviceinvheader, ashops s, adepartmentmaster d                   
  --where                   
  -- serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid           
  losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0 
 where                   
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends
   
  union all                  


  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002                  
  --credit           
  select           
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,                   
   0.0 ccashsales,                  
    convert(numeric(18,8), sum(redunitprice)) creditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehdepexrate)  dcreditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehexchangerate) ccreditsales,
   sum(redcostprice * redquantity) costvalue,                   
   sum(redcostprice * redquantity) * rehdepexrate dcostvalue, 
   sum(redcostprice * redquantity) * rehexchangerate ccostvalue,
   (convert(numeric(18,8), sum(redunitprice ))) -  sum(redcostprice * redquantity) margin,
   (convert(numeric(18,8), sum(redunitprice * rehdepexrate))) -                   
		sum(redcostprice * redquantity) * rehdepexrate dmargin,
   (convert(numeric(18,8), sum(redunitprice * rehexchangerate))) - 
		sum(redcostprice * redquantity) * rehexchangerate cmargin,                   
   departmentname, rehdepartmentid                  
 ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,0,0,0  
  from                   
   losExportDetail, losExportHeader, ashops s, adepartmentmaster d                   
  where                   
   rehExportID = redExportID and rehshopid = redshopid AND                   
   reHCANCELLED=0 and rehtype ='i' and                  
   rehproforma=0 and rehshopid = shopid and rehcashinvoice=0 and                   
   rehdepartmentid = d.departmentid                   
  group by                   
   shopname, rehshopid, departmentname, rehdepartmentid, rehExportDate,                   
   rehdepexrate, rehexchangerate,rehExportID                   
            
 union all                  
 -- added From Vwcashsales -Margin Not calculating                  
                   
 select                   
  s.shopname, vws.sishopid, vws.siinvoicedate,                   
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,                   
  convert(numeric(18,8),sum(vws.sidamount)) as  dcashsales,  -- RefNo-7 corrected amount                  
  convert(numeric(18,8),sum(vws.sicamount)) as ccashsales,   -- RefNo-7 corrected amount                                  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
   0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
  convert(numeric(18,8),sum(vws.siamount))as margin,    -- RefNo-7 included  -vws.GSTAmount                              
  convert(numeric(18,8),sum(vws.sidamount))as  dmargin,    -- RefNo-7 included  -vws.GSTAmount                               
  convert(numeric(18,8),sum(vws.sicamount))as cmargin,  -- RefNo-7 included  -vws.GSTAmount                              
  d.departmentname,lah.aidepartmentid  departmentid                   
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
  , sum(vws.dGSTAmount)as dGSTAmount  
  , sum(vws.cGSTAmount)as cGSTAmount  
 from                   
  vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d ,ashops s                  
 where                   
  aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
  aishopid = sishopid and lah.aicashinvoice=1 and       
  lah.aidepartmentid =d.departmentid and s.departmentid = d.departmentid                  
  and aiShopId = s.ShopId                  
 group by                   
  s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid, vws.siinvoicedate                  
  ,aidepexrate, aiexchangerate        
 union all                  
                  
    select s.shopname, vws.sishopid, vws.siinvoicedate,                   
    0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
    convert(numeric(18,8),sum(vws.siamount))as creditsales,                   
    convert(numeric(18,8),sum(vws.sidamount))as dcreditsales, -- RefNo-7 corrected amount                   
    convert(numeric(18,8),sum(vws.sidamount))as ccreditsales, -- RefNo-7 corrected amount                                    
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
    convert(numeric(18,8),sum(vws.siamount)) as margin,    -- RefNo-7 included  -vws.GSTAmount              
    convert(numeric(18,8),sum(vws.sidamount)) as dmargin,  -- RefNo-7 included  -vws.GSTAmount               
convert(numeric(18,8),sum(vws.sicamount)) as cmargin,  -- RefNo-7 included  -vws.GSTAmount   
    d.departmentname,lah.aidepartmentid  departmentid                   
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
    , sum(vws.dGSTAmount)as dGSTAmount  
    , sum(vws.cGSTAmount)as cGSTAmount  
    from vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d,ashops s      
    where aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
    aishopid = sishopid and lah.aicashinvoice=0 and lah.aidepartmentid =d.departmentid                  
    and s.departmentid = d.departmentid and s.ShopId = aiShopId group by                       
    s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid,vws.siinvoicedate,aiinvoiceid,
    aidepexrate                   
                   
    UniOn All -- added from vwCashSales                 
    --Shop debit credit notes and handling debit notes which are debit to the                
    -- customer and hence act as invoices to be settled                      
    Select  s.shopname,losdcnshopid,losdcndate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
    COnvert(numeric(18,8),Sum(losDCNAmount))  creditsales,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dcreditsales,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  ccreditsales,               
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    COnvert(numeric(18,8),Sum(losDCNAmount))  margin,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dmargin,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  cmargin,              
 d.departmentname,losdcndepartmentid                   
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2    
       ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount      
    From Ashops s,  losdebitcreditnote, adepartmentmaster d               
    Where  s.shopid = losdcnshopid And s.accountable Is Not Null                   
    And d.DepartmentID = losdcndepartmentid And losdcncancelled =0                    
    And losdcndebit =1  Group By s.shopname,d.departmentname,losdcnshopid,                  
    losdcndate, losdepexrate, losexchangerate,losdcndepartmentid              
              
    --hq serivce invoice dOne for shop                    
    Union all              
               
    Select  null, 0,ai.invoicedate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,          
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  creditsales,             
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dcreditsales,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  ccreditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)ccreditsales,         
  
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  margin,                     
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dmargin,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  cmargin,   
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)) * exchangerate)cmargin,        
                 
    d.departmentname,ai.departmentid           
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
     ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount   
     ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,  
      convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount  
  
  From accountsinvoiceheader ai, serviceinvoicedetails ser ,adepartmentmaster d              
    Where ai.invoiceid = ser.invoiceid And ai.companyid =                     
    ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0             
    and ai.departmentid = d.departmentid and ai.companyid = d.companyid               
    Group By  ai.invoicedate,depexrate,exchangerate,              
    d.departmentname,ai.departmentid              
        
  
 ----F&B---------------------------   
 --RefNo-5----------------------------------------------start----------------------------------------------------------------------------  
 ----------------------------------------  
 -- select v.* from        
 --(        
--select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales, 
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 --inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 --UNION ALL        
        
 --select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales,        
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,   
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 --inner join aitem a on a.itemid=fb_pd_dishid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 --where fb_pd_AddedItemtype=2        
 --)v       
  
/*  
union all  
  select shopname,poshShopID,poshBillDate,Cashsales,DepCashsales,ComCashsales,Creditsales,DepCreditsales,  
 ComCreditsales,costprice,dcostprice,ccostprice,margin,dmargin,cmargin,deptname,deptid,  
PdChequeSales,dPdChequeSales,cPdChequeSales  from  
 (        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid) costprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2        
  fb_pd_processdetailid  
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 UNION ALL        
        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2   
  fb_pd_processdetailid       
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 inner join aitem a on a.itemid=fb_pd_dishid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 where fb_pd_AddedItemtype=2        
  
  
 )  
  
  v        
 --RefNo-5----------------------------------------------end----------------------------------------------------------------------------  
  ----------------------------------------                  
  */  
     
 )cashcreditcollection      
group by                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid,                   
 cashcreditcollection.poshbilldate   
  

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID: sent by Bijesh on 24.08.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwshopservicesalesWithOutGST')
   DROP view dbo.vwshopservicesalesWithOutGST
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 --Last Modified on  : 19/10/2004    
--Modified by  : Aneesh  
------------------------------------------------------------------------------------------           
-- Modified by  : Bijesh.B  
-- Date         : 19/08/2011  
-- RefNo        : RefNo-5   
-- Ticket Id    : JSZ-828136 (SHEESHA)  
-- Description  : Need UserWise selection for Cash Denomination interface  
--              : siUserID column included  
------------------------------------------------------------------------------------------           
--RefNo        : Newly created view (copy of vwshopservicesales)  
--Modified by  : Bijesh.B  
--Date         : 13/03/2012,11/04/2012 (addes sum() in GST Amount)  
--Ticket id    : JDJ-400367 (Sonee)  
--comments     : Need to show GST separately  
----------------------------------------------------------------------------------------------     
--Modified by  : Bijesh.B  
--Date         : 09/07/2-12 
--Ticket id    : JDJ-400367 (Sonee)  
--comments     : Removde sum() in GST Amount, corrected sicamount and sidamount
----------------------------------------------------------------------------------------------     
    
create View vwshopservicesalesWithOutGST As  
    Select sicompanyid, sishopid, aiinvoicedate As siinvoicedate, aiinvoiceno, siinvoiceid,     
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then     
        ((Sum(siServiceQty * siAmount)) -IsNull(aiDiscount,0))   
    Else     
        (Sum((siServiceQty * siAmount) + siClearingCommAmt)) -IsNull(aiDiscount,0)  End  
        As siamount,

    Sum(aiSettledamount) Settledamount ,     
  
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then     
        Sum( ((siServiceQty * siAmount)- IsNull(aiDiscount,0)) * aiexchangerate)
    Else     
        Sum( (((siServiceQty * siAmount) + siClearingCommAmt) 
              -IsNull(aiDiscount,0))* aiexchangerate) End  As sicamount,     
       
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then     
        Sum(((siServiceQty * siAmount) -IsNull(aiDiscount,0))* aidepexrate) 
    Else     
        Sum((((siServiceQty * siAmount) + isnull(siClearingCommAmt,0)) 
			 -IsNull(aiDiscount,0))* aidepexrate)
			 End As sidamount       
		
    ,ISNULL(siUserID,0) as UserID  
    ,(isnull(aiTaxAmount,0)) GSTAmount  
    ,(isnull(aiTaxAmount,0) * aidepexrate) as dGSTAmount  
    ,(isnull(aiTaxAmount,0) * aiexchangerate) as cGSTAmount    
    From LOsServiceInvoiceDetails, LOsAccountsInvoiceHeader  
    Where aicancelled=0 And aiproforma=0 And aiinvoiceid = siinvoiceid And aishopid = sishopid   
    Group By sicompanyid, sishopid, aiinvoicedate,   
    siinvoiceid, aiinvoiceno, aiexchangerate,  aidepexrate,aiDiscount,isnull(aiTaxAmount,0),  
    Convert(Int, IsNull(aiCashPaidByShop,0)),ISNULL(siUserID,0)  

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

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionWithMarginGSTSeparately')
   DROP view dbo.vwDailySalesCollectionWithMarginGSTSeparately
GO


--Modified on           : 04/09/2004                  
--Modified by           : Hariharan                   
--Comments              : Added LOsAccountsInvoiceHeader                  
--   : Added lnvoiceheader - Id grouping                  
--   : included service details of service boooking invoices                    
--   : Corrected join condition of ashops with LOsAccountsInvoiceHeader                  
--   : Corrected the service invoice query to consider the repinvdtype field                
---------------------------------------------------------------------------------------                        
--Modified on                  : 22/11/2010               
--Modified by                  : Nidheesh P V                
--Comments                     : AddedF&B               
---------------------------------------------------------------------------------------                        
--RefNo        : RefNo-2        
--Modified by  : Bijesh.B        
--Date         : 16/06/2011, 21/06/2011        
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)        
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-3        
--Modified by  : Nidheesh P V       
--Date         : 16/06/2011        
--Comments     : Used -costprice instead of costprice       
--Modified Area: Daily Sales Report      
----------------------------------------------------------------------------------------------            
--RefNo        : RefNo-4      
--Modified by  : Bijesh.B      
--Date         : 29/07/2011      
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong      
--             : since, Special invoice return after desp, reqqty is negative,      
--     -1 is multiplied with reqqty      
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-5        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 19/01/2012  
--Comments     : Modified F&B part.  
----------------------------------------------------------------------------------------------         
----------------------------------------------------------------------------------------------         
--Created by   : Bijesh.B   
--Date         : 29/03/2012  
--Ticket id    : JDJ-400367 (new report (rptdailysalescollectionGSTSeparately) for sonee - GST separation)  
--Comments     : Created new view and report (Copy of vwDailySalesCollectionWithMargin)  
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-6        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 26/06/2012  
--Comments     : Exchage rate multiplication problem in POS  
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B    
--Date         : 07/07/2012  
--Comments     : Corrected Margin value for credit invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-7 
--Date         : 09/07/2012  
--Comments     : Corrected Margin value for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-8 
--Date         : 09/07/2012  
--Comments     : Corrected gst amount for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-9
--Date         : 30/07/2012  
--Comments     : Included Other Charges Service Tax in Credit Invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-10
--Date         : 11/08/2012  
--Comments     : Wrong tax amt is showing if same item with different packing type
--               is retuned in GRN
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-10
--Date         : 13/08/2012  
--Comments     : Corrected cost values in GRN in case if return 1 qty out of 2
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-11
--Date         : 16/08/2012  
--Comments     : Corrected credit sales values in case of two items having same type and one
--               normal item with 2 quantities each, and returning only 1 qty in grn.
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-12
--Date         : 17/08/2012  
--Comments     : Corrected credit sales values in case while deleting GRN.
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-13
--Date         : 25/08/2012  
--Comments     : Corrected serive module company wise cash sales figure and Margin
----------------------------------------------------------------------------------------------       

CREATE VIEW [dbo].[vwDailySalesCollectionWithMarginGSTSeparately] AS                  
Select                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.poshbilldate, convert(numeric(18,8),sum(cashsales)) cashsales,                  
 convert(numeric(18,8),sum(dcashsales)) dcashsales,                   
 convert(numeric(18,8),sum(ccashsales)) ccashsales,                  
 convert(numeric(18,8),sum(creditsales)) creditsales,                  
 convert(numeric(18,8),sum(dcreditsales)) dcreditsales,                   
 convert(numeric(18,8),sum(ccreditsales)) ccreditsales,                   
 convert(numeric(18,8),sum(costvalue)) costvalue,                  
 convert(numeric(18,8),sum(dcostvalue)) dcostvalue,                   
 convert(numeric(18,8),sum(ccostvalue)) ccostvalue,                   
 convert(numeric(18,8),sum(margin)) margin,                  
 convert(numeric(18,8),sum(dmargin)) dmargin, 
 convert(numeric(18,8),sum(cmargin)) cmargin,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid        
 --RefNo-2 start -------------------------        
,convert(numeric(18,8),sum(PdChequeSales)) PdChequeSales,        
convert(numeric(18,8),sum(dPdChequeSales)) dPdChequeSales,        
convert(numeric(18,8),sum(cPdChequeSales)) cPdChequeSales,        
--RefNo-2 ends -------------------------        
convert(numeric(18,8),sum(GSTAmount))GSTAmount,  
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,  
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount  
from                   
 (                  
  select                   
   shopname, poshShopID, poshbilldate,   
   --convert(numeric(18,8),sum(posdunitprice )) cashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)) ccashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dcashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8),sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -  
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))))
	 - sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -  
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   departmentname, poshdepartmentid  departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d                   
  where                   
   poshBillid=posdBillid and poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=0 --RefNo-2  if No PD Cheque Amt involved                       
  group by                   
   shopname, departmentname, poshdepartmentid, poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,poshBillid                  
        
--RefNo-2 Start --------------------------------------------        
--CASH + PD CHEQUE -> Taking only cash amount        
union all        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   --convert(numeric(18,8), 
   --sum(posdunitprice )) cashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshdepexrate)) dcashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshexchangerate)) ccashsales,        
     
   --convert(numeric(18,8),sum(posdunitprice)-pdCheque.PosBankAmount) cashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) dcashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) ccashsales,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8), sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -   
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))))) -   
        sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshdepexrate)) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -   
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
            
   departmentname, poshdepartmentid  departmentid                  
   --,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dPdChequeSales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) cPdChequeSales  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved        
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                            
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
  
/*        
union all        
--CASH + PD CHEQUE -> Taking only Cheque amount        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,        
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales,      
   /*      
   sum(posdcostprice * posdquantity) costvalue,                   
         
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
        
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
        
   (convert(numeric(18,8), sum(posdunitprice ))) -                   
   sum(posdcostprice*posdquantity) margin,      
         
   (convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -   
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin,       
         
   (convert(numeric(18,8), sum(posdunitprice * poshexchangerate))) -       
   sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   */      
   0.0 costvalue,0.0 dcostvalue,0.0 ccostvalue,       
   0.0 margin,0.0 dmargin,0.0 cmargin,        
   departmentname, poshdepartmentid  departmentid,                  
    pdCheque.PosBankAmount as PdChequeSales,        
   (pdCheque.PosBankAmount * poshdepexrate) as  dPdChequeSales,        
   (pdCheque.PosBankAmount * poshexchangerate) as cPdChequeSales        
  from                
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved          
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                          
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
--RefNo-2 ends --------------------------------------------        
*/                  
 union all                  

--RefNo-9 start commented and added                    
  --select                   
  -- shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
  -- --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
  -- --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
  -- --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
  -- convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,             
  -- convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,             
  -- convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,             
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -       
  -- --sum(isnull(idcostprice*idquantity,0)))) margin,                   
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
  -- --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
  -- --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -             
		-- sum(isnull(idcostprice*idquantity,0)))) margin,             
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		-- (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		--   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
  -- departmentname, ihdepartmentid departmentid                   
  -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
  -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
  -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
  -- convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  --from                   
  -- losinvoiceheader  ih                  
  -- left outer join losinvoicedetail invd                  
  -- on ihInvoiceid=idInvoiceid and ihshopid=idshopid     
  -- left outer join                   
  -- (select                  
  --  ioShopID,ioInvoiceID,sum(ioAmount) ioAmount                  
  -- from                  
  --  losInvoiceOC                   
  -- group by                  
  -- ioShopID,ioInvoiceID) ocd                   
  -- on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
  -- ashops s, adepartmentmaster d                   
  --where                   
  -- IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
  -- ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  --group by                   
  -- shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
  -- ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
    
  
   --credit invoice
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) creditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihexchangerate) ccreditsales,             

   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -      
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,  
                    
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) -             
		 sum(isnull(idcostprice*idquantity,0)))) margin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihexchangerate -             
		   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from          
    
     losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid
   
   union all
   
   --Other Charges
   
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   
   convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) creditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate) ccreditsales,             

   0 costvalue,                   
   0 dcostvalue,                  
   0 ccostvalue,                  
                    
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))Margin,            
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))* ihdepexrate  dmargin,             
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))) * ihexchangerate cmargin,  
   
 departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihexchangerate)cGSTAmount  
  
  from          
     losinvoiceheader  ih                  
   --left outer join losinvoicedetail invd  on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join losInvoiceOC ocd  on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID         
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by  
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid,ocd.ioShopID,ocd.ioInvoiceID
--RefNo-9 ends

 union all                  
                  
  select                   
   shopname, ihShopID, ihinvoicedate,                  
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) Cashsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,         
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,                   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,             
   0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -                   
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -             
		sum(isnull(idcostprice*idquantity,0)))) margin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from                   
   losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join                   
   (select                  
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount        
   from                  
    losInvoiceOC                   
   group by                  
   ioShopID,ioInvoiceID) ocd                   
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
   ashops s, adepartmentmaster d                   
  where                   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=1 and ihdepartmentid = d.departmentid and ihtype ='i'                  
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
                  
 union all                  
   select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehexchangerate)) ccashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
   0.0 creditsales,0.0 dcreditsales , 0.0 ccreditsales , sum(sedcostprice * sedquantity) costvalue,                  
   sum(sedcostprice * sedquantity) * sehdepexrate dcostvalue,                   
   sum(sedcostprice * sedquantity) * sehexchangerate ccostvalue,                  
   --convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedquantity) margin,  
   --convert(numeric(18,8), sum(sedunitprice* sehdepexrate)) -                   
 --sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   --convert(numeric(18,8), sum(sedunitprice * sehexchangerate )) -   
   --sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) - sum(sedcostprice * sedquantity) margin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) -                   
          sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) -   
          sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
    departmentname, sehdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d            
  where          
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and              
   sedbillorexchange = 'E' and sehshopid = shopid and sehdepartmentid = d.departmentid          
  group by      
   shopname, sehshopid, departmentname, sehdepartmentid, sehexchangedate ,                  
   departmentname,sehdepexrate, sehexchangerate,sehExchangeID                  
 union all                  
       
 -- RefNo-4 start  commented below      
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  sum(idunitprice )) cashsales, convert(numeric(18,8),                   
 ------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,8),                   
 ------  sum(idunitprice * ihexchangerate)) ccashsales,                  
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  (convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                   
 ------  (convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                   
 ------  (convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin, departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  ihdepartmentid =d.departmentid and idratetype=0 and ihproforma=0 and                   
 ------  ihshopid = shopid and ihcashinvoice=1 and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, departmentname, ihdepartmentid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
 ------ union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                   
 ------  0.0 ccashsales, convert(numeric(18,8), sum(idunitprice )) creditsales,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate)) dcreditsales,          
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate)) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                  
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                  
 ------  convert(numeric(18,8), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate) - sum(idcostprice*reqqty) * ihexchangerate) cmargin,                   
 ------  departmentname, ihDepartmentId departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  idratetype=0 and ihproforma=0 and ihshopid = shopid and                   
 ------  ihcashinvoice=0 and ihDepartmentId = d.departmentid                  
 ------  and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname, ihinvoicedate ,                   
 ------  ihexchangerate, ihdepexrate,ihInvoiceid   
               
 ------union all                  
 -- RefNo-4 ends      
                  
  select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),-sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehexchangerate)) ccashsales,                  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(-sedcostprice * sedExchangeQty) costvalue,    --RefNo-3              
   sum(-sedcostprice * sedExchangeQty) * sehdepexrate dcostvalue, sum(-sedcostprice * sedExchangeQty)     --RefNo-3             
   * sehexchangerate ccostvalue,  
    ---(convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedExchangeQty)) margin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -                   
   --    sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -   
    --    sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
           sum(sedcostprice * sedExchangeQty)) margin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -                   
        sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
        sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
  
   departmentname, sehdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d                   
  where        
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid                   
   and sehdepartmentid = d.departmentid                   
  group by                   
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,                  
   sehdepexrate,sedExchangeid                  
 union all       
       
 -- RefNo-4 start                  
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  -(sum(idunitprice ))) cashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihexchangerate))) ccashsales,                   
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(idcostprice * abs(reqqty)) costvalue,                   
 ------  sum(idcostprice * abs(reqqty)) * ihdepexrate dcostvalue, sum(idcostprice * abs(reqqty)) *                   
 ------  ihexchangerate ccostvalue,  -((convert(numeric(18,8), sum(idunitprice ))) -            
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0                    
 ------  and ihproforma=0 and ihshopid = shopid and ihTransfinished = 1                   
 ------  and ihcashinvoice=1 AND IDratetype=1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihdepartmentid, departmentname, ihshopid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
          
 ------union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice ))) creditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihdepexrate))) dcreditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihexchangerate))) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                   
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8),                   
 ------  sum(idunitprice ))) -  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND  
 ------  IHCANCELLED = 0 and ihproforma = 0 and ihshopid = shopid and                   
 ------  ihcashinvoice = 0 and idratetype = 1 and ihtransfinished = 1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname,                  
 ------  ihinvoicedate , ihexchangerate, ihdepexrate,ihInvoiceid                  
                  
 ------union all                  
      
-- special Invoice (cash)        
select         
shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccashsales,    
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales,   
  
0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty) margin,             
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,        
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty))* ihexchangerate cmargin,  
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d   
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                    
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all                                      
      
-------- special invoice - return before despatch                          
select shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,       
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-sum(idcostprice * reqqty) costvalue ,      
-sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
-sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
     
union all                                      
                                   
-- Special invoice return  - after desp                  
select shopname,                                     
 ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,     
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                        
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1         
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
-- special Invoice (credit)      
union all      
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccreditsales,    
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
       
 sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,      
--(convert(numeric(18,8), sum(idunitprice)))-sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))))-sum(idcostprice*reqqty) margin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice <>1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all         
      
-- special invoice - return before despatch                          
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,  
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,     
  
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
 -sum(idcostprice * reqqty) costvalue ,      
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) margin,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice <>1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                          
union all                                      
                                   
-- Special invoice return  - after desp                                    
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,  
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate))dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate))ccreditsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)dcreditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)ccreditsales,       
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
--idUnitPrice, idItemTaxAmount  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice <>1                                     
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
 -- RefNo-4 ends       
  union all                 

-- RefNo-10 start commented below and added
  --select                   
  -- shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) creditsales,                   
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                   
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   

  -- -sum(grncostprice*grndquantity) costvalue,
  -- - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                  
  -- -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,                   

  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))))-  
  --         sum(grncostprice*grndquantity)) margin,  
  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -                   
  --     sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -  
  --      sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,
                           
  -- departmentname, grnhdepartmentid departmentid                  
  -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
  -- ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
  -- ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
  --  -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  --from                   
  -- losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d                   
  --where               
  -- GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0                   
  -- and grnhshopid = shopid and grnhdepartmentid = d.departmentid                   
  --group by                   
  -- shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname, 
  -- grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID                  

select                   
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) creditsales,                   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                 
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   
   -- -sum(grncostprice*grndquantity) costvalue,
   -- -sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                  
   -- -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,  
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))costvalue,
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))* grnhdepexrate dcostvalue,                  
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))* grnhexchangerate ccostvalue,  

   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))))-  
           sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))) margin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) -                   
       sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity)))* grnhdepexRate dmargin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) -  
        sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))) * grnhExchangeRate cmargin,                   

   departmentname, grnhdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,-convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))GSTAmount  
   ,-convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
    -convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  from losgoodsreturnnoteheader 
   inner join losgoodsreturnnotedetail on  GrnhGoodsreturnnoteID = GRNDReturnNoteID 
		and grnhShopid = GRNDShopid
   inner join ashops s on  grnhshopid = shopid
   inner join adepartmentmaster d  on grnhdepartmentid = d.departmentid                   
   -- below linking with credit invoice was used since
   -- qty based on packing type was not available in GRN table
   left join  losinvoiceheader  ih on ih.ihInvoiceID = losgoodsreturnnoteheader.GrnhInvoiceID
		and ih.ihShopID = losgoodsreturnnoteheader.grnhShopid 
		and IHCANCELLED=0 and ihproforma=0 and ihshopid = s.shopid and    --RefNo-12 added                  
		ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'   --RefNo-12 added
		
   left outer join losinvoicedetail invd on ihInvoiceid=idInvoiceid and ihshopid=idshopid 
		and invd.idItemID = losgoodsreturnnotedetail.GRNDItemID --RefNo-11
		and invd.idPackingTypeID = losgoodsreturnnotedetail.grndPackTypeId
		and invd.idShopID = losgoodsreturnnotedetail.GRNDShopid
  where 
	   GrnhCancel =0                   
  group by                   
		shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,                   
		grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID 

-- RefNo-10 ends

  --hari added to include the service booking invoice parts replaced items                  
 UNION ALL                  
  
  --service invoice (cash)                
  select                   
   shopname, repinvdshopid, serinvhdate,  
   --convert(numeric(18,8),sum(repinvdrate* repinvdqty)) cashsales,  
   --convert(numeric(18,8),sum(repinvdrate* seinvhdepexrate * repinvdqty)) dcashsales,                 
   --convert(numeric(18,8),sum(repinvdrate* serinvhcmpexrate * repinvdqty)) ccashsales,                  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales,    
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales,   --RefNo-13                 

   0.0 creditsales, 0.0 dcreditsales , 0.0 ccreditsales ,  sum(repinvdcostprice * repinvdqty) costvalue,                   
   sum(repinvdcostprice * repinvdqty) * seinvhdepexrate  dcostvalue,  
   sum(repinvdcostprice * repinvdqty) *serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -  
   --  sum(repinvdcostprice * repinvdqty),                   
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,   
   --convert(numeric(18,8),(sum(repinvdrate  * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty)margin,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))  
      -sum(repinvdcostprice * repinvdqty)) *  seinvhdepexrate dmargin,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))  
 -sum(repinvdcostprice * repinvdqty)) *  serinvhcmpexrate cmargin,          
  
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --RefNo-8  start commneted, since this gst amount is taken care in below
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
 --convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
   ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
--RefNo-8 ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d                   
  where                   
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1                  
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, serinvhDepartmentid,                   
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid                   
                  
 union all                  
 
  --service Details  (cash)                
  select                   
   shopname, serinvhshopid, serinvhdate,  
   --convert(numeric(18,8) , serinvhserviceamt) cashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccashsales ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales ,  --RefNo-13 changed bracket           
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                       
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,           
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,    
   
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)),          
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,       
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) *  serinvhcmpexrate) ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales ,             

   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount  
  from                   
--RefNo-8 start commented below
   --losserviceinvheader, ashops s, adepartmentmaster d                   
	 --where                   
	 --  serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1         
	 --  and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                  
   
 losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid   and Patindex('%y%',repinvdtype)>0 
 where                   
	serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1  
    and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends 
 union all
  
  --service invoice (credit)	    
    select                   
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , (sum(repinvdrate* repinvdqty))) creditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * seinvhdepexrate * repinvdqty))) dcreditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * serinvhcmpexrate * repinvdqty))) ccreditsales ,   
  
   convert(numeric(18,8),(sum( (repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccreditsales ,             
                     
   sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*                   
   seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty), convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty) * seinvhdepexrate , convert(numeric(18,8) ,                   
   --( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate ,                   
   
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))-sum(repinvdcostprice * repinvdqty)) * seinvhdepexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))-sum(repinvdcostprice * repinvdqty)) * serinvhcmpexrate,  

   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  --RefNo-8  start commneted, since this gst amount is taken care in below
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
	 -- convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
	,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
  --RefNo-8  ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader,                   
   ashops s, adepartmentmaster d 
  where 
   serinvhid = repinvinvoiceid and                   
   serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is null                   
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid                    
   and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,                  
   serinvhcmpexrate ,serinvhid   
   
   union all
          
  --service Details   (credit)               
  select                   
 shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , serinvhserviceamt) creditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcreditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccreditsales ,     
   
   --RefNo-8 start commented below
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) creditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate) dcreditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate) ccreditsales ,             
   convert(numeric(18,8),serinvhserviceamt- (isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) creditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcreditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccreditsales ,             
   --RefNo-8 ends
   
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))*seinvhdepexrate ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))*serinvhcmpexrate ,             
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount    
  from                   
  --RefNo-8 start commented below
  -- losserviceinvheader, ashops s, adepartmentmaster d                   
  --where                   
  -- serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid           
  losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0 
 where                   
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends
   
  union all                  


  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002                  
  --credit           
  select           
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,                   
   0.0 ccashsales,                  
    convert(numeric(18,8), sum(redunitprice)) creditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehdepexrate)  dcreditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehexchangerate) ccreditsales,
   sum(redcostprice * redquantity) costvalue,                   
   sum(redcostprice * redquantity) * rehdepexrate dcostvalue, 
   sum(redcostprice * redquantity) * rehexchangerate ccostvalue,
   (convert(numeric(18,8), sum(redunitprice ))) -  sum(redcostprice * redquantity) margin,
   (convert(numeric(18,8), sum(redunitprice * rehdepexrate))) -                   
		sum(redcostprice * redquantity) * rehdepexrate dmargin,
   (convert(numeric(18,8), sum(redunitprice * rehexchangerate))) - 
		sum(redcostprice * redquantity) * rehexchangerate cmargin,                   
   departmentname, rehdepartmentid                  
 ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,0,0,0  
  from                   
   losExportDetail, losExportHeader, ashops s, adepartmentmaster d                   
  where                   
   rehExportID = redExportID and rehshopid = redshopid AND                   
   reHCANCELLED=0 and rehtype ='i' and                  
   rehproforma=0 and rehshopid = shopid and rehcashinvoice=0 and                   
   rehdepartmentid = d.departmentid                   
  group by                   
   shopname, rehshopid, departmentname, rehdepartmentid, rehExportDate,                   
   rehdepexrate, rehexchangerate,rehExportID                   
            
 union all                  
 -- added From Vwcashsales -Margin Not calculating                  
                   
 select                   
  s.shopname, vws.sishopid, vws.siinvoicedate,                   
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,                   
  convert(numeric(18,8),sum(vws.sidamount)) as  dcashsales,  -- RefNo-7 corrected amount                  
  convert(numeric(18,8),sum(vws.sicamount)) as ccashsales,   -- RefNo-7 corrected amount                                  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
   0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
  convert(numeric(18,8),sum(vws.siamount))as margin,    -- RefNo-7 included  -vws.GSTAmount                              
  convert(numeric(18,8),sum(vws.sidamount))as  dmargin,    -- RefNo-7 included  -vws.GSTAmount                               
  convert(numeric(18,8),sum(vws.sicamount))as cmargin,  -- RefNo-7 included  -vws.GSTAmount                              
  d.departmentname,lah.aidepartmentid  departmentid                   
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
  , sum(vws.dGSTAmount)as dGSTAmount  
  , sum(vws.cGSTAmount)as cGSTAmount  
 from                   
  vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d ,ashops s                  
 where                   
  aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
  aishopid = sishopid and lah.aicashinvoice=1 and       
  lah.aidepartmentid =d.departmentid and s.departmentid = d.departmentid                  
  and aiShopId = s.ShopId                  
 group by                   
  s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid, vws.siinvoicedate                  
  ,aidepexrate, aiexchangerate        
 union all                  
                  
    select s.shopname, vws.sishopid, vws.siinvoicedate,                   
    0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
    convert(numeric(18,8),sum(vws.siamount))as creditsales,                   
    convert(numeric(18,8),sum(vws.sidamount))as dcreditsales, -- RefNo-7 corrected amount                   
    convert(numeric(18,8),sum(vws.sidamount))as ccreditsales, -- RefNo-7 corrected amount                                    
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
    convert(numeric(18,8),sum(vws.siamount)) as margin,    -- RefNo-7 included  -vws.GSTAmount              
    convert(numeric(18,8),sum(vws.sidamount)) as dmargin,  -- RefNo-7 included  -vws.GSTAmount               
convert(numeric(18,8),sum(vws.sicamount)) as cmargin,  -- RefNo-7 included  -vws.GSTAmount   
    d.departmentname,lah.aidepartmentid  departmentid                   
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
    , sum(vws.dGSTAmount)as dGSTAmount  
    , sum(vws.cGSTAmount)as cGSTAmount  
    from vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d,ashops s      
    where aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
    aishopid = sishopid and lah.aicashinvoice=0 and lah.aidepartmentid =d.departmentid                  
    and s.departmentid = d.departmentid and s.ShopId = aiShopId group by                       
    s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid,vws.siinvoicedate,aiinvoiceid,
    aidepexrate                   
                   
    UniOn All -- added from vwCashSales                 
    --Shop debit credit notes and handling debit notes which are debit to the                
    -- customer and hence act as invoices to be settled                      
    Select  s.shopname,losdcnshopid,losdcndate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
    COnvert(numeric(18,8),Sum(losDCNAmount))  creditsales,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dcreditsales,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  ccreditsales,               
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    COnvert(numeric(18,8),Sum(losDCNAmount))  margin,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dmargin,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  cmargin,              
 d.departmentname,losdcndepartmentid                   
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2    
       ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount      
    From Ashops s,  losdebitcreditnote, adepartmentmaster d               
    Where  s.shopid = losdcnshopid And s.accountable Is Not Null                   
    And d.DepartmentID = losdcndepartmentid And losdcncancelled =0                    
    And losdcndebit =1  Group By s.shopname,d.departmentname,losdcnshopid,                  
    losdcndate, losdepexrate, losexchangerate,losdcndepartmentid           
              
    --hq serivce invoice dOne for shop                    
    Union all              
               
    Select  null, 0,ai.invoicedate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,          
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  creditsales,             
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dcreditsales,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  ccreditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)ccreditsales,         
  
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  margin,                     
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dmargin,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  cmargin,   
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)) * exchangerate)cmargin,        
                 
    d.departmentname,ai.departmentid           
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
     ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount   
     ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,  
      convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount  
  
  From accountsinvoiceheader ai, serviceinvoicedetails ser ,adepartmentmaster d              
    Where ai.invoiceid = ser.invoiceid And ai.companyid =                     
    ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0             
    and ai.departmentid = d.departmentid and ai.companyid = d.companyid               
    Group By  ai.invoicedate,depexrate,exchangerate,              
    d.departmentname,ai.departmentid              
        
  
 ----F&B---------------------------   
 --RefNo-5----------------------------------------------start----------------------------------------------------------------------------  
 ----------------------------------------  
 -- select v.* from        
 --(        
--select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales, 
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 --inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 --UNION ALL        
        
 --select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
--when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales,        
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,   
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 --inner join aitem a on a.itemid=fb_pd_dishid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 --where fb_pd_AddedItemtype=2        
 --)v       
  
/*  
union all  
  select shopname,poshShopID,poshBillDate,Cashsales,DepCashsales,ComCashsales,Creditsales,DepCreditsales,  
 ComCreditsales,costprice,dcostprice,ccostprice,margin,dmargin,cmargin,deptname,deptid,  
PdChequeSales,dPdChequeSales,cPdChequeSales  from  
 (        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid) costprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2        
  fb_pd_processdetailid  
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 UNION ALL        
        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2   
  fb_pd_processdetailid       
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 inner join aitem a on a.itemid=fb_pd_dishid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 where fb_pd_AddedItemtype=2        
  
  
 )  
  
  v        
 --RefNo-5----------------------------------------------end----------------------------------------------------------------------------  
  ----------------------------------------                  
  */  
     
 )cashcreditcollection      
group by                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid,                   
 cashcreditcollection.poshbilldate   


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

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionWithMarginGSTSeparately')
   DROP view dbo.vwDailySalesCollectionWithMarginGSTSeparately
GO


--Modified on           : 04/09/2004                  
--Modified by           : Hariharan                   
--Comments              : Added LOsAccountsInvoiceHeader                  
--   : Added lnvoiceheader - Id grouping                  
--   : included service details of service boooking invoices                    
--   : Corrected join condition of ashops with LOsAccountsInvoiceHeader                  
--   : Corrected the service invoice query to consider the repinvdtype field                
---------------------------------------------------------------------------------------                        
--Modified on                  : 22/11/2010               
--Modified by                  : Nidheesh P V                
--Comments                     : AddedF&B               
---------------------------------------------------------------------------------------                        
--RefNo        : RefNo-2        
--Modified by  : Bijesh.B        
--Date         : 16/06/2011, 21/06/2011        
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)        
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-3        
--Modified by  : Nidheesh P V       
--Date         : 16/06/2011        
--Comments     : Used -costprice instead of costprice       
--Modified Area: Daily Sales Report      
----------------------------------------------------------------------------------------------            
--RefNo        : RefNo-4      
--Modified by  : Bijesh.B      
--Date         : 29/07/2011      
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong      
--             : since, Special invoice return after desp, reqqty is negative,      
--     -1 is multiplied with reqqty      
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-5        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 19/01/2012  
--Comments     : Modified F&B part.  
----------------------------------------------------------------------------------------------         
----------------------------------------------------------------------------------------------         
--Created by   : Bijesh.B   
--Date         : 29/03/2012  
--Ticket id    : JDJ-400367 (new report (rptdailysalescollectionGSTSeparately) for sonee - GST separation)  
--Comments     : Created new view and report (Copy of vwDailySalesCollectionWithMargin)  
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-6        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 26/06/2012  
--Comments     : Exchage rate multiplication problem in POS  
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B    
--Date         : 07/07/2012  
--Comments     : Corrected Margin value for credit invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-7 
--Date         : 09/07/2012  
--Comments     : Corrected Margin value for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-8 
--Date         : 09/07/2012  
--Comments     : Corrected gst amount for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-9
--Date         : 30/07/2012  
--Comments     : Included Other Charges Service Tax in Credit Invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-10
--Date         : 11/08/2012  
--Comments     : Wrong tax amt is showing if same item with different packing type
--               is retuned in GRN
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-10
--Date         : 13/08/2012  
--Comments     : Corrected cost values in GRN in case if return 1 qty out of 2
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-11
--Date         : 16/08/2012  
--Comments     : Corrected credit sales values in case of two items having same type and one
--               normal item with 2 quantities each, and returning only 1 qty in grn.
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-12
--Date         : 17/08/2012  
--Comments     : Corrected credit sales values in case while deleting GRN.
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-13
--Date         : 25/08/2012  
--Comments     : Corrected serive module company wise cash sales figure and Margin
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--Date         : 05/09/2012  
--Comments     : Corrected Pos-Service invoice figures
----------------------------------------------------------------------------------------------       

create VIEW [dbo].[vwDailySalesCollectionWithMarginGSTSeparately] AS                  
Select                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.poshbilldate, convert(numeric(18,8),sum(cashsales)) cashsales,                  
 convert(numeric(18,8),sum(dcashsales)) dcashsales,                   
 convert(numeric(18,8),sum(ccashsales)) ccashsales,                  
 convert(numeric(18,8),sum(creditsales)) creditsales,                  
 convert(numeric(18,8),sum(dcreditsales)) dcreditsales,                   
 convert(numeric(18,8),sum(ccreditsales)) ccreditsales,                   
 convert(numeric(18,8),sum(costvalue)) costvalue,                  
 convert(numeric(18,8),sum(dcostvalue)) dcostvalue,                   
 convert(numeric(18,8),sum(ccostvalue)) ccostvalue,                   
 convert(numeric(18,8),sum(margin)) margin,                  
 convert(numeric(18,8),sum(dmargin)) dmargin, 
 convert(numeric(18,8),sum(cmargin)) cmargin,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid        
 --RefNo-2 start -------------------------        
,convert(numeric(18,8),sum(PdChequeSales)) PdChequeSales,        
convert(numeric(18,8),sum(dPdChequeSales)) dPdChequeSales,        
convert(numeric(18,8),sum(cPdChequeSales)) cPdChequeSales,        
--RefNo-2 ends -------------------------        
convert(numeric(18,8),sum(GSTAmount))GSTAmount,  
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,  
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount  
from                   
 (                  
  select                   
   shopname, poshShopID, poshbilldate,   
   --convert(numeric(18,8),sum(posdunitprice )) cashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)) ccashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dcashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8),sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -  
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))))
	 - sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -  
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   departmentname, poshdepartmentid  departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d                   
  where                   
   poshBillid=posdBillid and poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=0 --RefNo-2  if No PD Cheque Amt involved                       
  group by                   
   shopname, departmentname, poshdepartmentid, poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,poshBillid                  
        
--RefNo-2 Start --------------------------------------------        
--CASH + PD CHEQUE -> Taking only cash amount        
union all        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   --convert(numeric(18,8), 
   --sum(posdunitprice )) cashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshdepexrate)) dcashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshexchangerate)) ccashsales,        
     
   --convert(numeric(18,8),sum(posdunitprice)-pdCheque.PosBankAmount) cashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) dcashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) ccashsales,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8), sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -   
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))))) -   
        sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshdepexrate)) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -   
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
            
   departmentname, poshdepartmentid  departmentid                  
   --,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dPdChequeSales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) cPdChequeSales  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved        
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                            
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         

  

  
/*        
union all        
--CASH + PD CHEQUE -> Taking only Cheque amount        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,        
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales,      
   /*      
   sum(posdcostprice * posdquantity) costvalue,                   
         
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
        
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
        
   (convert(numeric(18,8), sum(posdunitprice ))) -                   
   sum(posdcostprice*posdquantity) margin,      
         
   (convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -   
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin,       
         
   (convert(numeric(18,8), sum(posdunitprice * poshexchangerate))) -       
   sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   */      
   0.0 costvalue,0.0 dcostvalue,0.0 ccostvalue,       
   0.0 margin,0.0 dmargin,0.0 cmargin,        
   departmentname, poshdepartmentid  departmentid,                  
    pdCheque.PosBankAmount as PdChequeSales,        
   (pdCheque.PosBankAmount * poshdepexrate) as  dPdChequeSales,        
   (pdCheque.PosBankAmount * poshexchangerate) as cPdChequeSales        
  from                
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved          
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                          
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
--RefNo-2 ends --------------------------------------------        
*/                  
 union all         

--RefNo-9 start commented and added                    
  --select                   
  -- shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
  -- --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
  -- --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
  -- --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
  -- convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,             
  -- convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,             
  -- convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,             
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -       
  -- --sum(isnull(idcostprice*idquantity,0)))) margin,                   
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
  -- --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
  -- --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -             
		-- sum(isnull(idcostprice*idquantity,0)))) margin,             
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		-- (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		--   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
  -- departmentname, ihdepartmentid departmentid                   
  -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
  -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
  -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
  -- convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  --from                   
  -- losinvoiceheader  ih                  
  -- left outer join losinvoicedetail invd                  
  -- on ihInvoiceid=idInvoiceid and ihshopid=idshopid     
  -- left outer join                   
  -- (select                  
  --  ioShopID,ioInvoiceID,sum(ioAmount) ioAmount                  
  -- from                  
  --  losInvoiceOC                   
  -- group by                  
  -- ioShopID,ioInvoiceID) ocd                   
  -- on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
  -- ashops s, adepartmentmaster d                   
  --where                   
  -- IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
  -- ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  --group by                   
  -- shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
  -- ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
    
  
   --credit invoice
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) creditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihexchangerate) ccreditsales,             

   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -      
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,  
                    
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) -             
		 sum(isnull(idcostprice*idquantity,0)))) margin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihexchangerate -             
		   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from          
    
     losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid
   
   union all
   
   --Other Charges
   
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   
   convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) creditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate) ccreditsales,             

   0 costvalue,                   
   0 dcostvalue,                  
   0 ccostvalue,                  
                    
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))Margin,            
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))* ihdepexrate  dmargin,             
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))) * ihexchangerate cmargin,  
   
 departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihexchangerate)cGSTAmount  
  
  from          
     losinvoiceheader  ih                  
   --left outer join losinvoicedetail invd  on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join losInvoiceOC ocd  on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID         
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by  
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid,ocd.ioShopID,ocd.ioInvoiceID
--RefNo-9 ends

 union all                  
                  
  select                   
   shopname, ihShopID, ihinvoicedate,                  
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) Cashsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,         
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,                   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,             
   0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -                   
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -             
		sum(isnull(idcostprice*idquantity,0)))) margin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from                   
   losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join                   
   (select                  
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount        
   from                  
    losInvoiceOC                   
   group by                  
   ioShopID,ioInvoiceID) ocd                   
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
   ashops s, adepartmentmaster d                   
  where                   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=1 and ihdepartmentid = d.departmentid and ihtype ='i'                  
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
                  
 union all                  
   select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehexchangerate)) ccashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
   0.0 creditsales,0.0 dcreditsales , 0.0 ccreditsales , sum(sedcostprice * sedquantity) costvalue,                  
   sum(sedcostprice * sedquantity) * sehdepexrate dcostvalue,                   
   sum(sedcostprice * sedquantity) * sehexchangerate ccostvalue,                  
   --convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedquantity) margin,  
   --convert(numeric(18,8), sum(sedunitprice* sehdepexrate)) -                   
 --sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   --convert(numeric(18,8), sum(sedunitprice * sehexchangerate )) -   
   --sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) - sum(sedcostprice * sedquantity) margin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) -                   
          sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) -   
          sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
    departmentname, sehdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d            
  where          
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and              
   sedbillorexchange = 'E' and sehshopid = shopid and sehdepartmentid = d.departmentid          
  group by      
   shopname, sehshopid, departmentname, sehdepartmentid, sehexchangedate ,                  
   departmentname,sehdepexrate, sehexchangerate,sehExchangeID                  
 union all                  
       
 -- RefNo-4 start  commented below      
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  sum(idunitprice )) cashsales, convert(numeric(18,8),                   
 ------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,8),                   
 ------  sum(idunitprice * ihexchangerate)) ccashsales,                  
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  (convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                   
 ------  (convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                   
 ------  (convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin, departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  ihdepartmentid =d.departmentid and idratetype=0 and ihproforma=0 and                   
 ------  ihshopid = shopid and ihcashinvoice=1 and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, departmentname, ihdepartmentid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
 ------ union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                   
 ------  0.0 ccashsales, convert(numeric(18,8), sum(idunitprice )) creditsales,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate)) dcreditsales,          
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate)) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                  
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                  
 ------  convert(numeric(18,8), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate) - sum(idcostprice*reqqty) * ihexchangerate) cmargin,                   
 ------  departmentname, ihDepartmentId departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  idratetype=0 and ihproforma=0 and ihshopid = shopid and                   
 ------  ihcashinvoice=0 and ihDepartmentId = d.departmentid                  
 ------  and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname, ihinvoicedate ,                   
 ------  ihexchangerate, ihdepexrate,ihInvoiceid   
               
 ------union all                  
 -- RefNo-4 ends      
                  
  select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),-sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehexchangerate)) ccashsales,                  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(-sedcostprice * sedExchangeQty) costvalue,    --RefNo-3              
   sum(-sedcostprice * sedExchangeQty) * sehdepexrate dcostvalue, sum(-sedcostprice * sedExchangeQty)     --RefNo-3             
   * sehexchangerate ccostvalue,  
    ---(convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedExchangeQty)) margin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -                   
   --    sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -   
    --    sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
           sum(sedcostprice * sedExchangeQty)) margin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -                   
        sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
        sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
  
   departmentname, sehdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d                   
  where        
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid                   
   and sehdepartmentid = d.departmentid                   
  group by                   
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,                  
   sehdepexrate,sedExchangeid                  
 union all       
       
 -- RefNo-4 start                  
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  -(sum(idunitprice ))) cashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihexchangerate))) ccashsales,                   
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(idcostprice * abs(reqqty)) costvalue,                   
 ------  sum(idcostprice * abs(reqqty)) * ihdepexrate dcostvalue, sum(idcostprice * abs(reqqty)) *                   
 ------  ihexchangerate ccostvalue,  -((convert(numeric(18,8), sum(idunitprice ))) -            
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0                    
 ------  and ihproforma=0 and ihshopid = shopid and ihTransfinished = 1                   
 ------  and ihcashinvoice=1 AND IDratetype=1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihdepartmentid, departmentname, ihshopid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
          
 ------union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice ))) creditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihdepexrate))) dcreditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihexchangerate))) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                   
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8),                   
 ------  sum(idunitprice ))) -  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND  
 ------  IHCANCELLED = 0 and ihproforma = 0 and ihshopid = shopid and                   
 ------  ihcashinvoice = 0 and idratetype = 1 and ihtransfinished = 1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname,                  
 ------  ihinvoicedate , ihexchangerate, ihdepexrate,ihInvoiceid                  
                  
 ------union all                  
      
-- special Invoice (cash)        
select         
shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccashsales,    
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales,   
  
0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty) margin,             
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,        
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty))* ihexchangerate cmargin,  
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d   
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                    
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all                                      
      
-------- special invoice - return before despatch                          
select shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,       
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-sum(idcostprice * reqqty) costvalue ,      
-sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
-sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
     
union all                                      
                                   
-- Special invoice return  - after desp                  
select shopname,                                     
 ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,     
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                        
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1         
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
-- special Invoice (credit)      
union all      
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccreditsales,    
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
       
 sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,      
--(convert(numeric(18,8), sum(idunitprice)))-sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))))-sum(idcostprice*reqqty) margin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice <>1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all         
      
-- special invoice - return before despatch                          
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,  
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
  
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
 -sum(idcostprice * reqqty) costvalue ,      
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) margin,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice <>1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                          
union all                                      
                                   
-- Special invoice return  - after desp                                    
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,  
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate))dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate))ccreditsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)dcreditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)ccreditsales,       
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
--idUnitPrice, idItemTaxAmount  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice <>1                                     
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
 -- RefNo-4 ends       
  union all                 

-- RefNo-10 start commented below and added
  --select                   
  -- shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) creditsales,                   
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                   
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   

  -- -sum(grncostprice*grndquantity) costvalue,
  -- - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                  
  -- -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,                   

  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))))-  
  --         sum(grncostprice*grndquantity)) margin,  
  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -                   
  --     sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -  
  --      sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,
                           
  -- departmentname, grnhdepartmentid departmentid                  
  -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
  -- ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
  -- ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
  --  -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  --from                   
  -- losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d                   
  --where               
  -- GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0                   
  -- and grnhshopid = shopid and grnhdepartmentid = d.departmentid                   
  --group by                   
  -- shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname, 
  -- grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID                  

select                   
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) creditsales,                   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                 
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   
   -- -sum(grncostprice*grndquantity) costvalue,
   -- -sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                  
   -- -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,  
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))costvalue,
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))* grnhdepexrate dcostvalue,                  
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))* grnhexchangerate ccostvalue,  

   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))))-  
           sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))) margin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) -                   
       sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity)))* grnhdepexRate dmargin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) -  
        sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))) * grnhExchangeRate cmargin,                   

   departmentname, grnhdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,-convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))GSTAmount  
   ,-convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
    -convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  from losgoodsreturnnoteheader 
   inner join losgoodsreturnnotedetail on  GrnhGoodsreturnnoteID = GRNDReturnNoteID 
		and grnhShopid = GRNDShopid
   inner join ashops s on  grnhshopid = shopid
   inner join adepartmentmaster d  on grnhdepartmentid = d.departmentid                   
   -- below linking with credit invoice was used since
   -- qty based on packing type was not available in GRN table
   left join  losinvoiceheader  ih on ih.ihInvoiceID = losgoodsreturnnoteheader.GrnhInvoiceID
		and ih.ihShopID = losgoodsreturnnoteheader.grnhShopid 
		and IHCANCELLED=0 and ihproforma=0 and ihshopid = s.shopid and    --RefNo-12 added                  
		ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'   --RefNo-12 added
		
   left outer join losinvoicedetail invd on ihInvoiceid=idInvoiceid and ihshopid=idshopid 
		and invd.idItemID = losgoodsreturnnotedetail.GRNDItemID --RefNo-11
		and invd.idPackingTypeID = losgoodsreturnnotedetail.grndPackTypeId
		and invd.idShopID = losgoodsreturnnotedetail.GRNDShopid
  where 
	   GrnhCancel =0                   
  group by                   
		shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,                   
		grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID 

-- RefNo-10 ends

  --hari added to include the service booking invoice parts replaced items                  
 UNION ALL                  
  
  --service invoice (cash)                
  select                   
   shopname, repinvdshopid, serinvhdate,  
   --convert(numeric(18,8),sum(repinvdrate* repinvdqty)) cashsales,  
   --convert(numeric(18,8),sum(repinvdrate* seinvhdepexrate * repinvdqty)) dcashsales,  
   --convert(numeric(18,8),sum(repinvdrate* serinvhcmpexrate * repinvdqty)) ccashsales,                  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales,    
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales,   --RefNo-13                 

   0.0 creditsales, 0.0 dcreditsales , 0.0 ccreditsales ,  sum(repinvdcostprice * repinvdqty) costvalue,                   
   sum(repinvdcostprice * repinvdqty) * seinvhdepexrate  dcostvalue,  
   sum(repinvdcostprice * repinvdqty) *serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -  
   --  sum(repinvdcostprice * repinvdqty),                   
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,   
   --convert(numeric(18,8),(sum(repinvdrate  * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty)margin,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))  
      -sum(repinvdcostprice * repinvdqty)) *  seinvhdepexrate dmargin,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))  
 -sum(repinvdcostprice * repinvdqty)) *  serinvhcmpexrate cmargin,          
  
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --RefNo-8  start commneted, since this gst amount is taken care in below
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
 --convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
   ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
--RefNo-8 ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d                   
  where                   
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1                  
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, serinvhDepartmentid,                   
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid                   
                  
 union all                  
 
  --service Details  (cash)                
  select                   
   shopname, serinvhshopid, serinvhdate,  
   --convert(numeric(18,8) , serinvhserviceamt) cashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccashsales ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales ,  --RefNo-13 changed bracket           
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                       
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,           
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,    
   
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)),          
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,       
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) *  serinvhcmpexrate) ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales ,             

   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount  
  from                   
--RefNo-8 start commented below
   --losserviceinvheader, ashops s, adepartmentmaster d                   
	 --where                   
	 --  serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1         
	 --  and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                  
   
 losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid   and Patindex('%y%',repinvdtype)>0 
 where                   
	serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1  
    and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends 
 union all
  
  --service invoice (credit)	    
    select                   
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , (sum(repinvdrate* repinvdqty))) creditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * seinvhdepexrate * repinvdqty))) dcreditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * serinvhcmpexrate * repinvdqty))) ccreditsales ,   
  
   convert(numeric(18,8),(sum( (repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccreditsales ,             
                     
   sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*                   
   seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty), convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty) * seinvhdepexrate , convert(numeric(18,8) ,                   
   --( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate ,                   
   
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))-sum(repinvdcostprice * repinvdqty)) * seinvhdepexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))-sum(repinvdcostprice * repinvdqty)) * serinvhcmpexrate,  

   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  --RefNo-8  start commneted, since this gst amount is taken care in below
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
	 -- convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
	,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
  --RefNo-8  ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader,                   
   ashops s, adepartmentmaster d 
  where 
   serinvhid = repinvinvoiceid and                   
   serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is null                   
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid                    
   and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,                  
   serinvhcmpexrate ,serinvhid   
   
   union all
          
  --service Details   (credit)               
  select                   
 shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , serinvhserviceamt) creditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcreditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccreditsales ,     
   
   --RefNo-8 start commented below
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) creditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate) dcreditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate) ccreditsales ,             
   convert(numeric(18,8),serinvhserviceamt- (isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) creditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcreditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccreditsales ,             
   --RefNo-8 ends
   
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))*seinvhdepexrate ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))*serinvhcmpexrate ,             
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount    
  from                   
  --RefNo-8 start commented below
  -- losserviceinvheader, ashops s, adepartmentmaster d                   
  --where                   
  -- serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid           
  losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0 
 where                   
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends
   
  union all                  


  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002                  
  --credit           
  select           
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,                   
   0.0 ccashsales,                  
    convert(numeric(18,8), sum(redunitprice)) creditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehdepexrate)  dcreditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehexchangerate) ccreditsales,
   sum(redcostprice * redquantity) costvalue,                   
   sum(redcostprice * redquantity) * rehdepexrate dcostvalue, 
   sum(redcostprice * redquantity) * rehexchangerate ccostvalue,
   (convert(numeric(18,8), sum(redunitprice ))) -  sum(redcostprice * redquantity) margin,
   (convert(numeric(18,8), sum(redunitprice * rehdepexrate))) -                   
		sum(redcostprice * redquantity) * rehdepexrate dmargin,
   (convert(numeric(18,8), sum(redunitprice * rehexchangerate))) - 
		sum(redcostprice * redquantity) * rehexchangerate cmargin,                   
   departmentname, rehdepartmentid                  
 ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,0,0,0  
  from                   
   losExportDetail, losExportHeader, ashops s, adepartmentmaster d                   
  where                   
   rehExportID = redExportID and rehshopid = redshopid AND                   
   reHCANCELLED=0 and rehtype ='i' and                  
   rehproforma=0 and rehshopid = shopid and rehcashinvoice=0 and                   
   rehdepartmentid = d.departmentid                   
  group by                   
   shopname, rehshopid, departmentname, rehdepartmentid, rehExportDate,                   
   rehdepexrate, rehexchangerate,rehExportID                   
            
 union all                  
 -- added From Vwcashsales -Margin Not calculating                  
                   
 select                   
  s.shopname, vws.sishopid, vws.siinvoicedate,                   
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,                   
  convert(numeric(18,8),sum(vws.sidamount)) as  dcashsales,  -- RefNo-7 corrected amount                  
  convert(numeric(18,8),sum(vws.sicamount)) as ccashsales,   -- RefNo-7 corrected amount                                  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
   0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
  convert(numeric(18,8),sum(vws.siamount))as margin,    -- RefNo-7 included  -vws.GSTAmount                              
  convert(numeric(18,8),sum(vws.sidamount))as  dmargin,    -- RefNo-7 included  -vws.GSTAmount                               
  convert(numeric(18,8),sum(vws.sicamount))as cmargin,  -- RefNo-7 included  -vws.GSTAmount                              
  d.departmentname,lah.aidepartmentid  departmentid                   
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
  , sum(vws.dGSTAmount)as dGSTAmount  
  , sum(vws.cGSTAmount)as cGSTAmount  
 from                   
  vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d ,ashops s                  
 where                   
  aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
  aishopid = sishopid and lah.aicashinvoice=1 and       
  lah.aidepartmentid =d.departmentid and s.departmentid = d.departmentid                  
  and aiShopId = s.ShopId                  
 group by                   
  s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid, vws.siinvoicedate                  
  ,aidepexrate, aiexchangerate        
 union all                  
                  
    select s.shopname, vws.sishopid, vws.siinvoicedate,                   
    0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
    convert(numeric(18,8),sum(vws.siamount))as creditsales,                   
    convert(numeric(18,8),sum(vws.sidamount))as dcreditsales, -- RefNo-7 corrected amount                   
    convert(numeric(18,8),sum(vws.sicamount))as ccreditsales, -- RefNo-7 corrected amount                                    
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
    convert(numeric(18,8),sum(vws.siamount)) as margin,    -- RefNo-7 included  -vws.GSTAmount              
    convert(numeric(18,8),sum(vws.sidamount)) as dmargin,  -- RefNo-7 included  -vws.GSTAmount               
convert(numeric(18,8),sum(vws.sicamount)) as cmargin,  -- RefNo-7 included  -vws.GSTAmount   
    d.departmentname,lah.aidepartmentid  departmentid                   
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
    , sum(vws.dGSTAmount)as dGSTAmount  
    , sum(vws.cGSTAmount)as cGSTAmount  
    from vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d,ashops s      
    where aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
    aishopid = sishopid and lah.aicashinvoice=0 and lah.aidepartmentid =d.departmentid                  
    and s.departmentid = d.departmentid and s.ShopId = aiShopId group by                       
    s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid,vws.siinvoicedate,aiinvoiceid,
    aidepexrate                   
                   
    UniOn All -- added from vwCashSales                 
    --Shop debit credit notes and handling debit notes which are debit to the                
    -- customer and hence act as invoices to be settled                      
    Select  s.shopname,losdcnshopid,losdcndate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
    COnvert(numeric(18,8),Sum(losDCNAmount))  creditsales,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dcreditsales,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  ccreditsales,               
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    COnvert(numeric(18,8),Sum(losDCNAmount))  margin,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dmargin,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  cmargin,              
 d.departmentname,losdcndepartmentid                   
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2    
       ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount      
    From Ashops s,  losdebitcreditnote, adepartmentmaster d               
    Where  s.shopid = losdcnshopid And s.accountable Is Not Null                   
    And d.DepartmentID = losdcndepartmentid And losdcncancelled =0                    
    And losdcndebit =1  Group By s.shopname,d.departmentname,losdcnshopid,                  
    losdcndate, losdepexrate, losexchangerate,losdcndepartmentid           
              
    --hq serivce invoice dOne for shop                    
    Union all              
               
    Select  null, 0,ai.invoicedate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,          
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  creditsales,             
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dcreditsales,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  ccreditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)ccreditsales,         
  
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  margin,                     
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dmargin,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  cmargin,   
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)) * exchangerate)cmargin,        
                 
    d.departmentname,ai.departmentid           
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
     ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount   
     ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,  
      convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount  
  
  From accountsinvoiceheader ai, serviceinvoicedetails ser ,adepartmentmaster d              
    Where ai.invoiceid = ser.invoiceid And ai.companyid =                     
    ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0             
    and ai.departmentid = d.departmentid and ai.companyid = d.companyid               
    Group By  ai.invoicedate,depexrate,exchangerate,              
    d.departmentname,ai.departmentid              
        
  
 ----F&B---------------------------   
 --RefNo-5----------------------------------------------start----------------------------------------------------------------------------  
 ----------------------------------------  
 -- select v.* from        
 --(        
--select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales, 
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 --inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 --UNION ALL        
        
 --select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00  
--when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales,        
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,   
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 --inner join aitem a on a.itemid=fb_pd_dishid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 --where fb_pd_AddedItemtype=2        
 --)v       
  
/*  
union all  
  select shopname,poshShopID,poshBillDate,Cashsales,DepCashsales,ComCashsales,Creditsales,DepCreditsales,  
 ComCreditsales,costprice,dcostprice,ccostprice,margin,dmargin,cmargin,deptname,deptid,  
PdChequeSales,dPdChequeSales,cPdChequeSales  from  
 (        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid) costprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2        
  fb_pd_processdetailid  
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 UNION ALL        
        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2   
  fb_pd_processdetailid       
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 inner join aitem a on a.itemid=fb_pd_dishid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 where fb_pd_AddedItemtype=2        
  
  
 )  
  
  v        
 --RefNo-5----------------------------------------------end----------------------------------------------------------------------------  
  ----------------------------------------                  
  */  
     
 )cashcreditcollection      
group by                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid,                   
 cashcreditcollection.poshbilldate   
  
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:XLW-768367 
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

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

USE [adminv2]
GO

/****** Object:  View [dbo].[vwLocalPurchaseInvoiceDetails]    Script Date: 09/11/2012 09:38:32 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- Created By : MANUNADH. U  
-- Created On : 06-09-2012  
-- Purpose    : To create a new report for showing relations of Item, vendor and customer   
--    during a period of time.   
CREATE VIEW [dbo].[vwLocalPurchaseInvoiceDetails] as  
SELECT DISTINCT VW.lphBillDate BillDate,VW.lphVendorID VendorID,V.VendorName,VW.lpditemid Itemid,  
 VW.itemdescription,VW.lphbillid Billid,VW.lphBillNo BillNo,VW.lpdItemQuantity PurchaseQuantity,  
 VW.lpdItemUnitPrice PurchaseUnitPrice,VW.unitname,VW.lpdItemTaxAmount BillItemTaxAmount,  
 IH.ihInvoiceDate InvoiceDate,IH.ihinvoiceid Invoiceid,IH.ihinvoiceno Invoiceno,ID.idQuantity SoldQuantity,  
 ID.idUnitPrice SoldUnitPrice,ID.idItemTaxAmount InvItemTaxAmount,IH.ihCustomerID CustomerID,C.CustomerName,
 VW.lphshopid ShopId  
FROM vwlocalpurchasebill VW   
 INNER JOIN LosLocalPurchaseInvoiceDetails LPID ON LPID.lpidBillId=VW.lphbillid AND   
  LPID.lpidShopId=VW.lphshopid AND LPID.lpidItemId=VW.lpditemid  
 INNER JOIN losinvoiceheader IH ON IH.ihinvoiceid=LPID.lpidInvoiceId AND IH.ihShopID=LPID.lpidShopId  
 INNER JOIN LOsInvoiceDetail ID ON ID.idInvoiceID=IH.ihInvoiceID AND ID.idShopID=IH.ihShopID  
  AND LPID.lpidItemId=ID.iditemid  
 INNER JOIN aVendorMaster V ON V.VendorID=VW.lphVendorID  
 INNER JOIN aCustomerMaster C ON C.CustomerID=IH.ihCustomerID  
WHERE VW.lphCancelled=0 AND IH.ihCancelled=0 --AND VW.lphshopid=2 AND lpditemid=1838  
  
GO


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

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

USE [adminv2]
GO

/****** Object:  View [dbo].[vwCollectedSalesTax]    Script Date: 09/11/2012 18:18:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

                      
------------------------------------------------------------------------------------------                               
-- Modified by  : Nidheesh P V                            
-- Date         : 19/10/2011                            
-- Comments  : To get total collected sales tax.                          
-- Just copy the view vwcashsales and just excluded the Sales Returns such as goodr return,                          
--exchnage,Spl inv return.                          
------------------------------------------------------------------------------------------                                     
 -- Modified by  : Jyothish S R                         
-- Date         : 03/11/2011 ,17-11-2011                      
--- Comments  : To  Bill No  is added and hire purchase recipt added             
---(ocd.TaxAmount),0)+ ISNULL(sum(invd.idItemTaxAmount) added in credit invoice         
---bonded  custom amount is added         
--vws.siamount + isnull(aiTaxAmount,0) added in Shop service (cash)    
--booking advances  tax amount is correct           
------------------------------------------------------------------------------------------                               
-- Modified by  : Rajesh Kamalakshan                           
-- Date         : 24/11/2011                            
-- Comments  :Increased precision to 9 digits ,so as to get accuracy in GST report                     
------------------------------------------------------------------------------------------                                     
-- Modified by  : MANUNADH. U
-- RefNo		: RefNo:1
-- Date         : 11/09/2012                            
-- Comments		: GST figure adding Twice and Sales Figure shows wrong in GST report                    
------------------------------------------------------------------------------------------  
create  View [dbo].[vwCollectedSalesTax]                          
As                              
                          
--Cash Sales                          
Select poshcompanyid As companyid, poshshopid As shopid, poshbilldate As billdate,                                 
	poshcAshaccid As accountid, COnvert(numeric(18,9), Sum( posdunitprice ))  As amount,                                
	COnvert(numeric(18,9), Sum( posdunitprice ) * poshdepexrate)  As damount,                                
	COnvert(numeric(18,9), Sum( posdunitprice) * poshexchangerate) As camount,1 As cAsh, 
	'p' As transtype, poshdepartmentid departmentid ,0 as PdChqCancelled,ISNULL(poshUserId,0) as UserID                          
	,isnull(posdItemTaxPercentage,0) as TaxPercentage                          
	,COnvert(numeric(18,9), Sum(posdItemTaxAmount)) As TaxAmount                         
	,COnvert(numeric(18,9), Sum( posdItemTaxAmount ) * poshdepexrate)  As DTaxAmount                               
	,COnvert(numeric(18,9), Sum( posdItemTaxAmount) * poshexchangerate) As CTaxAmount,poshBillNo,
	isnull(posdItemTaxCategory,0) as posdItemTaxCategory                         
From  losposheader ph,losposdetail pd   
Where ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0                                 
--and isnull(ph.PosPostDate,0)<>1 --and isnull(posdItemTaxPercentage,0)<>0                          
Group By poshcompanyid , poshshopid , poshbilldate ,poshbillid, poshcAshaccid,poshdepartmentid, 
	poshbillamount,poshdepexrate, poshexchangerate,ISNULL(poshUserId,0),posdItemTaxPercentage,
	poshBillNo, posdItemTaxCategory                          
                        
UNION ALL                            
                          
--Exchnage new Sales                          
Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,
	COnvert(numeric(18,9),Sum(sedunitprice)) As amount,                                
	COnvert(numeric(18,9),Sum(sedunitprice) * sehdepexrate) As damount,                                
	COnvert(numeric(18,9),Sum(sedunitprice) * sehexchangerate) As camount,1,'e'  As transtype, 
	sehdepartmentid departmentid,0 as PdChqCancelled,ISNULL(sehUserID,0) as UserID                          
	,isnull(sedItemTaxPercentage,0),COnvert(numeric(18,9), Sum(sedItemTaxAmount))TaxAmount                        
	,COnvert(numeric(18,9), Sum( sedItemTaxAmount ) * sehdepexrate)  As dTaxAmount                               
	,COnvert(numeric(18,9), Sum( sedItemTaxAmount) * sehexchangerate) As cTaxAmount,sehExchangeNo,
	isnull(sedItemTaxCategory ,0)                                      
From losposexchangeheader ph, losposexchangedetail pd                                 
Where ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid And                                 
	sehcancelled=0 And sedbillorexchange ='E'                         
--and isnull(sedItemTaxPercentage,0)<>0                             
Group By sehcompanyid,sehshopid, sehexchangedate, sehexchangeid,sehcAshaccid, sehdepartmentid, 
sehdepexrate, sehexchangerate,ISNULL(sehUserID,0),sedItemTaxPercentage,sehExchangeNo,sedItemTaxCategory                        
                            
Union All                                

-- special Invoice (cash)                              
select ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
	convert(numeric(18, 9),sum(idUnitPrice)) amount,
	convert(numeric(18, 9),sum(idUnitPrice * ihDepExRate)) damount,                            
	convert(numeric(18, 9),sum(idUnitPrice * ihExchangeRate)) camount,1, 'd' As transtype, 
	ihdepartmentid departmentid  ,0 as PdChqCancelled,ISNULL(ihUserId,0) as UserID                          
	,isnull(idItemTaxPercentage,0),COnvert(numeric(18,9), Sum(idItemTaxAmount))TaxAmount                         
	,COnvert(numeric(18,9), Sum( idItemTaxAmount ) * ihDepExRate)  As dTaxAmount                               
	,COnvert(numeric(18,9), Sum( idItemTaxAmount) * ihExchangeRate) As cTaxAmount,IhInvoiceNo,
	isnull(idItemTaxCategory,0)                                         
from losspecialinvoicedetail, losspecialinvoiceheader                                                             
where ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and idratetype = 0 and 
	ihproforma = 0 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0                          
-- and isnull(idItemTaxPercentage,0)<>0                                                       
Group By ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,                                 
 ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0),idItemTaxPercentage ,IhInvoiceNo,idItemTaxCategory                              
                                                         
union all                                     
                            
---- special invoice (cash) - return before despatch                                                 
--select --ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,                                 
--convert(numeric(18, 2),-sum(idUnitPrice)) amount,                            
--convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) damount,                            
--convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) camount,                                             
--1, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled                               
--,ISNULL(ihUserId,0) as UserID --,idItemTaxPercentage --,COnvert(numeric(18,2), -Sum(idItemTaxAmount))                                      
--from -- losspecialinvoicedetail,losspecialinvoiceheader                                                            
--where -- ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                                             
-- idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1                             
-- and ihNoofOCDetails<>0 --Group By                              
-- ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,                                 
-- ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0),idItemTaxPercentage                            
                                                                
--union all                                                            
                                                         
---- Special invoice return (cash)  - after desp                                                          
--select -- ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,                            
-- convert(numeric(18, 2),-sum(idUnitPrice)) amount,                            
-- convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) damount,                             
-- convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) camount,                                                             
-- 1, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled                             
-- ,ISNULL(ihUserId,0) as UserID -- ,idItemTaxPercentage                             
-- ,COnvert(numeric(18,2), -Sum(idItemTaxAmount))                                      
--from -- losspecialinvoicedetail,losspecialinvoiceheader                                                            
--where -- ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                  
-- idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1                                                           
--Group By -- ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,                                 
-- ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0),idItemTaxPercentage                             
                             
-- union all                           
                           
-- special Invoice (credit)                            
                          
select ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
	convert(numeric(18, 9),sum(idUnitPrice)) amount,                            
	convert(numeric(18, 9),sum(idUnitPrice * ihDepExRate)) damount,                            
	convert(numeric(18, 9),sum(idUnitPrice * ihExchangeRate)) camount,0, 'd' As transtype, 
	ihdepartmentid departmentid,0 as PdChqCancelled ,ISNULL(ihUserId,0) as UserID                           
	,isnull(idItemTaxPercentage,0),COnvert(numeric(18,9), Sum(idItemTaxAmount)) TaxAmount                                      
	,COnvert(numeric(18,9), Sum(idItemTaxAmount ) * ihDepExRate)  As dTaxAmount                               
	,COnvert(numeric(18,9), Sum( idItemTaxAmount) * ihExchangeRate) As cTaxAmount ,IhInvoiceNo,
	isnull(idItemTaxCategory,0)                               
from losspecialinvoicedetail, losspecialinvoiceheader                                                             
where ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and idratetype = 0 and 
	ihproforma = 0 and IhTransFinished = 1 And ihcAshinvoice<>1 and ihNoofOCDetails=0                         
 --and isnull(idItemTaxPercentage,0)<>0                                                      
Group By  ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,                                 
 ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0),idItemTaxPercentage,IhInvoiceNo,idItemTaxCategory                            
                                                         
union all                                                            
                            
---- special invoice(credit) - return before despatch                                                
--select  --ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,                                 
--convert(numeric(18, 2),-sum(idUnitPrice)) amount,                            
--convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) damount,                            
--convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) camount,             
--0, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled                               
--,ISNULL(ihUserId,0) as UserID --,idItemTaxPercentage                             
--,COnvert(numeric(18,2), -Sum(idItemTaxAmount))                                      
--from  -- losspecialinvoicedetail,losspecialinvoiceheader                                                            
--where -- ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                                             
-- idratetype = 0 and ihproforma = 0 And ihcAshinvoice<>1 and ihTransFinished = 1                             
-- and ihNoofOCDetails<>0                                                        
--Group By -- ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,                                 
-- ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0) ,idItemTaxPercentage                            
                                                                
--union all                                                            
                                                         
---- Special invoice return(credit)  - after desp                                                          
--select -- ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,                            
-- convert(numeric(18, 2),-sum(idUnitPrice)) amount,                            
-- convert(numeric(18, 2),-sum(idUnitPrice * ihDepExRate)) damount,                             
-- convert(numeric(18, 2),-sum(idUnitPrice * ihExchangeRate)) camount,                                                             
-- 0, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled                             
--,ISNULL(ihUserId,0) as UserID --,idItemTaxPercentage                             
--,COnvert(numeric(18,2), -Sum(idItemTaxAmount))                                      
--from -- losspecialinvoicedetail,losspecialinvoiceheader                                                            
--where -- ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                    
-- idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice<>1                                                           
--Group By -- ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,                                 
-- ihdepexrate, ihexchangerate,ISNULL(ihUserId,0),idItemTaxPercentage                             
                           
-- UniOn All                                
                          
-----Exchange                          
--Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,                                 
--COnvert(numeric(18,2),-Sum(sedunitprice)) As amount,                                 
--COnvert(numeric(18,2),-Sum(sedunitprice) * sehdepexrate) As damount,                                
--COnvert(numeric(18,2),-Sum(sedunitprice) * sehexchangerate) As camount, 1,                          
--'e' As transtype, sehdepartmentid  departmentid ,0 as PdChqCancelled                              
--,ISNULL(sehUserID,0) as UserID --,sedItemTaxPercentage                           
--,COnvert(numeric(18,2),CONVERT(numeric(18,2),-Sum(isnull(sedItemTaxAmount,0))))                          
--From   losposexchangeheader ph, losposexchangedetail pd                                
--Where ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid                                 
--And sehcancelled=0 And sedbillorexchange ='B' And sedexchangeqty > 0                                
--Group By sehcompanyid, sehshopid, sehexchangedate, sehexchangeid, sehcAshaccid,                                 
--sehdepartmentid, sehdepexrate, sehexchangerate,ISNULL(sehUserID,0),sedItemTaxPercentage                           
         
--UniOn All                            
                              
--Credit Invoice Other Charge                          
Select ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,                                 
	Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then                                 
	(Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0))                               
	Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))  End Amount,                                 
	Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then                                 
	(Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0)) * ihdepexrate                              
	Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))* ihdepexrate  End DAmount,                                 
	Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then                                 
	(Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0)) * ihExchangeRate                               
	Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))* ihExchangeRate End cAmount,                               
	1,'c' As transtype, ih.ihdepartmentid  departmentid ,0 as PdChqCancelled                              
	,ISNULL(ihuserid,0) as UserID,invd.idItemTaxPercentage,                          
	convert(numeric(18,9), isnull(Sum(ocd.TaxAmount),0)+ ISNULL(sum(invd.idItemTaxAmount),0 )) TaxAmount                          
	,convert(numeric(18,9),isnull(Sum(ocd.TaxAmount),0)+ ISNULL(sum(invd.idItemTaxAmount),0 )* ihdepexrate ) DTaxAmount                        
	,convert(numeric(18,9),isnull(Sum(ocd.TaxAmount),0)+ ISNULL(sum(invd.idItemTaxAmount),0 ) * ihExchangeRate ) CTaxAmount ,ihInvoiceNo,isnull(idItemTaxCategory,0)                        
From  losinvoiceheader ih 
Left Outer Join losinvoicedetail invd On ih.ihshopid = invd.idshopid                                
	And ih.ihinvoiceid = invd.idinvoiceid  Left Outer Join                                
	(Select ioShopID,ioInvoiceID,Sum(ioAmount) ioAmount,isnull(ioServTaxPerc,0) as TaxPerc,sum(isnull(ioServTaxAmount,0))TaxAmount  From losInvoiceOC                                 
		Group By   ioShopID,ioInvoiceID,ioServTaxPerc
	) ocd  On ihshopid= ocd.ioShopid And ihinvoiceid=ocd.ioInvoiceID, Ashops s   
Where ihcancelled=0 And ihcAshinvoice = 1 And ih.ihproforma =0 And ih.ihtype='I'                                
 And ihshopid = s.shopid And ihcompanyid = s.COmpanyid                         
 --and ocd.TaxPerc<>0                               
Group By ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid,                               
	ihdepartmentid,  ihdepexrate, ihexchangerate, ocd.ioAmount, s.futurevarchar,                            
	ih.ihdutypaidby,ISNULL(ihuserid,0),invd.idItemTaxPercentage,ihInvoiceNo,idItemTaxCategory                          
                                
UniOn All                                
                          
--Shop service (cash)                                
Select vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,   
--<<RefNo:1>>-Comment the Previous code and add new code since  siamount is Tax added amount                        
 --COnvert(numeric(18,9),(vws.siamount + isnull(aiTaxAmount,0)  )) As amount,                                 
 --COnvert(numeric(18,9),(vws.siamount + isnull(aiTaxAmount,0) * aidepexrate)) As damount,                                
 --COnvert(numeric(18,9),(vws.siamount + isnull(aiTaxAmount,0) * aiexchangerate)) As camount, 
 --New Code
 COnvert(numeric(18,9),vws.siamount ) As amount,                                 
 COnvert(numeric(18,9),(vws.siamount  * aidepexrate)) As damount,                                
 COnvert(numeric(18,9),(vws.siamount  * aiexchangerate)) As camount, 
 --New Code                               
--<<RefNo:1>>-Comment the Previous code and add new code since  siamount is Tax added amount                        
 lah.aicAshinvoice , 's' As transtype, aidepartmentid departmentid ,0 as PdChqCancelled                                
 ,ISNULL(vws.UserID,0) as UserID                        
 ,isnull(aiTaxPercentage,0) ,COnvert(numeric(18,9),isnull(aiTaxAmount,0))TaxAmount                  
 ,COnvert(numeric(18,9),(isnull(aiTaxAmount,0) * aidepexrate)) As DTaxAmount                               
 ,COnvert(numeric(18,9),(isnull(aiTaxAmount,0) * aiexchangerate)) As CTaxAmount ,vws.aiinvoiceno ,ISNULL(aiTaxCategory,0)                           
From     vwshopservicesales vws , LOsAccountsInvoiceHeader lah, vwshops s                                
Where  s.shopid = aIshopid And aiinvoiceid=siinvoiceid And aicancelled=0 And                                 
 aiproforma=0 And aIshopid = sIshopid And lah.aicAshinvoice =1                        
-- and isnull(aiTaxPercentage,0)<>0                            
                                
UniOn All                                
--hq serivce invoice dOne for shop (cash)                               
Select                                 
 ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,                                 
 COnvert(numeric(18,9),Sum(serviceqty * amount) ),                                
 COnvert(numeric(18,9),Sum(serviceqty * amount) *depexrate),                                
 COnvert(numeric(18,9),Sum(serviceqty * amount) *exchangerate),                                
 1 ,'hs', ai.departmentid  departmentid  ,0 as PdChqCancelled                                
 ,ISNULL(ser.UserID,0) as UserID                          
 ,isnull(TaxPercentage,0), COnvert(numeric(18,9),Sum(isnull(TaxAmount,0)))TaxAmount                        
 ,COnvert(numeric(18,9),Sum(isnull(TaxAmount,0)) *depexrate) DTaxAmount                              
 ,COnvert(numeric(18,9),Sum(isnull(TaxAmount,0)) *exchangerate) CTaxAmount,InvoiceNo,ISNULL(ItemTaxCategory,0)                              
From                                 
 accountsinvoiceheader ai, serviceinvoicedetails ser                                 
Where                                 
 ai.invoiceid = ser.invoiceid And ai.companyid =                                 
 ser.companyid And ai.cAshinvoice = 1 And ai.cancelled = 0 And ai.proforma = 0                         
 and isnull(TaxPercentage,0)<>0                                
Group By                               
 ai.companyid, ai.invoicedate,ai.invoiceid,ai.exchangerate,ai.bankcAshid,                                 
 ai.departmentid, depexrate, exchangerate ,ISNULL(ser.UserID,0),TaxPercentage , InvoiceNo,ItemTaxCategory                          
                                
UniOn All                                
                                
-- hari included From credit sales to correct the daily sales Summary report                                
Select                                 
 ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,                                 
 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then                                 
 (Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0)+Isnull(Sum(invd.idcdcustcur),0) ) -- +Isnull(Sum(invd.idcdcustcur),0)                                
 Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))  End Amount,                                 
 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then                                 
 (Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0)+ Isnull(Sum(invd.idcdcustcur),0) ) * ihdepexrate --  +Isnull(Sum(invd.idcdcustcur),0)                                
 Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))* ihdepexrate  End DAmount,                                 
 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then                                 
 (Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0)+ Isnull(Sum(invd.idcdcustcur),0)   ) * ihExchangeRate -- +Isnull(Sum(invd.idcdcustcur),0)                                
 Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))* ihExchangeRate End cAmount,                                 
 0 ihcAshinvoice, 'c' As transtype, ih.ihdepartmentid  departmentid ,0 as PdChqCancelled                       
,ISNULL(ihuserid,0) as UserID                          
 ,invd.idItemTaxPercentage                        
 ,convert(numeric(18,9),SUM(isnull(ServTaxAmount,0)) ++ ISNULL(sum(invd.idItemTaxAmount),0 ) )                        
 ,convert(numeric(18,9),SUM(isnull(ServTaxAmount,0))+ + ISNULL(sum(invd.idItemTaxAmount),0 ) * ihdepexrate ) DTaxAmount                        
,convert(numeric(18,9),SUM(isnull(ServTaxAmount,0))++ ISNULL(sum(invd.idItemTaxAmount),0 ) * ihExchangeRate ) CTaxAmount,ihInvoiceNo,ISNULL(idItemTaxCategory,0)                           
From                                 
 losinvoiceheader ih                                 
 Left Outer Join losinvoicedetail invd                                 
 On ih.ihshopid = invd.idshopid And ih.ihinvoiceid = invd.idinvoiceid                                
 Left Outer Join                                 
 (Select                    
  ioShopID,ioInvoiceID,Sum(ioAmount) ioAmount                           
  ,isnull(ioServTaxPerc,0) as ServTaxPerc,sum(isnull(ioServTaxAmount,0))ServTaxAmount                               
 From                                
  losInvoiceOC                                 
 Group By                               
  ioShopID,ioInvoiceID,ioServTaxPerc) ocd                                 
 On ihshopid= ocd.ioShopid And ihinvoiceid=ocd.ioInvoiceID, Ashops s                            
Where                                 
 ihcancelled=0 And ihcAshinvoice =0 And ih.ihproforma =0 And ih.ihtype='I'                                
 And ihshopid = s.shopid And ihcompanyid = s.COmpanyid                        
-- and ServTaxPerc<>0                                
Group By                              
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,                                 
 ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate, ocd.ioAmount,                                 
 s.futurevarchar, ih.ihdutypaidby,ISNULL(ihuserid,0),invd.idItemTaxPercentage ,ihInvoiceNo ,idItemTaxCategory                                   
                                
UniOn All                                
                                
--serviceinvoice (credit)                               
Select                                 
 vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,              
 COnvert(numeric(18,9),vws.siamount+isnull(aiTaxAmount,0)) As amount,                                 
 COnvert(numeric(18,9),(vws.siamount+isnull(aiTaxAmount,0)) * aidepexrate) As damount,                                 
 COnvert(numeric(18,9),(vws.siamount+isnull(aiTaxAmount,0)) * aiexchangerate) As camount, lah.aicAshinvoice,                            
  's' As transtype, lah.aidepartmentid  departmentid ,0 as PdChqCancelled                         
,ISNULL(vws.UserID,0) as UserID                          
,isnull(aiTaxPercentage,0),COnvert(numeric(18,9),isnull(aiTaxAmount,0))                        
 ,COnvert(numeric(18,9),isnull(aiTaxAmount,0) * aidepexrate) As dTaxAmount                                
 ,COnvert(numeric(18,9),isnull(aiTaxAmount,0) * aiexchangerate) As cTaxAmount, vws.aiinvoiceno ,isnull( aiTaxCategory,0)                      
From                                 
 vwshopservicesales vws , LOsAccountsInvoiceHeader lah                                
Where                                 
 aiinvoiceid=siinvoiceid And aicancelled=0 And aiproforma=0 And aIshopid = sIshopid                                
 And lah.aicAshinvoice=0-- and isnull(aiTaxPercentage,0)<>0                           
                            
-- hari included                             
UniOn All                                
                          
--hq serivce invoice dOne for shop (credit)                               
Select                                 
 ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,                                 
 COnvert(numeric(18,9),Sum(serviceqty * amount) ),                                 
 COnvert(numeric(18,9),Sum(serviceqty * amount) * depexrate),                                
 COnvert(numeric(18,9),Sum(serviceqty * amount) * exchangerate),                                
 0 ,'hs',ai.departmentid  departmentid   ,0 as PdChqCancelled                               
,ISNULL(ser.UserID,0) as UserID                           
,isnull(TaxPercentage,0)                            
,COnvert(numeric(18,9),Sum(isnull(TaxAmount,0))) TaxAmount                        
 ,COnvert(numeric(18,9),Sum(isnull(TaxAmount,0)) * depexrate) DTaxAmount                               
 ,COnvert(numeric(18,9),Sum(isnull(TaxAmount,0)) * exchangerate)CTaxAmount ,InvoiceNo ,ISNULL( ItemTaxCategory,0)                        
From                                 
 accountsinvoiceheader ai, serviceinvoicedetails ser                                 
Where                                 
 ai.invoiceid = ser.invoiceid And ai.companyid =                                 
 ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0                         
 --and isnull(TaxPercentage,0)<>0                                
Group By                              
 ai.companyid, ai.invoicedate, ai.invoiceid, ai.exchangerate,ai.bankcAshid,                                 
 ai.departmentid, depexrate, exchangerate,ISNULL(ser.UserID,0),TaxPercentage ,InvoiceNo ,ItemTaxCategory                           
                                
                             
UniOn All                                
                          
-- hari included for service booking advances                            
                          
--Service Booking Advnce                               
Select                                 
 serbookhcompanyid, serbookhshopid, serbookadvancedate, serbookhcAshacc,                                 
 COnvert(numeric(18,9), serbookadvanceamount) ,                                
 COnvert(numeric(18,9), serbookadvanceamount * serbookhdepexrate),                                
 COnvert(numeric(18,9), serbookadvanceamount * serbookhcmpexrate), 1  ,'sb',                                 
 serbookhdepartmentid ,0 as PdChqCancelled                             
,ISNULL(serbookhUserid,0) as UserID                          
,0  as taxperc                           
,COnvert(numeric(18,9), sum(isnull(serinvhTaxamount*0,0))) as taxamnt                         
,COnvert(numeric(18,9), sum(isnull(serinvhTaxamount*0,0))* serbookhdepexrate) as Dtaxamnt                          
,COnvert(numeric(18,9), sum(isnull(serinvhTaxamount*0,0))* serbookhcmpexrate) as Ctaxamnt,serbookhInspectionNo  ,0                       
From LOsServiceBookingHeader inner join                            
 losbookservicedetails                         
 on serbkdbookid=serbookhid                        
 and  serbkdshopid=serbookhshopid                              
Where                                 
 serbookhinpcancelled=0                                 
 And serbookadvanceamount>0                                
-- and isnull(serinvhTaxPercentage,0)<>0                        
 group by  serbookhcompanyid, serbookhshopid, serbookadvancedate, serbookhcAshacc,serbookadvanceamount                        
 ,serbookhdepexrate,serbookhcmpexrate,serbookhdepartmentid,serbookhUserid,serbookhInspectionNo                       
             
-- hari included for service booking invoices which are cAsh invoices                                
UniOn All                                
                                
Select                                 
 serinvhcompanyid, serinvhshopid, serinvhdate, serinvhcAshacc,                                 
 COnvert(numeric(18,9), serinvhamount) ,                                 
 COnvert(numeric(18,9), serinvhamount * seinvhdepexrate) ,                                 
 COnvert(numeric(18,9), serinvhamount * serinvhcmpexrate) , 1 , 'sbi',                                 
 serinvhdepartmentid  ,0 as PdChqCancelled                             
,ISNULL(serinvhuserid,0) as UserID                           
,isnull(serinvhTaxPercentage,0) as taxperc                           
,COnvert(numeric(18,9), isnull(serinvhTaxamount,0)) as taxamnt                         
,COnvert(numeric(18,9), isnull(serinvhTaxamount,0)* seinvhdepexrate) as Dtaxamnt                          
,COnvert(numeric(18,9), isnull(serinvhTaxamount,0)* serinvhcmpexrate) as Ctaxamnt,serinvno,serinvhTaxCateID                                
From                                 
 losserviceinvheader                           
Where                                 
 serinvhcancelled = 0   And                                 
 serinvhamount>0 And serinvhcAshacc Is Not Null                         
-- and isnull(serinvhTaxPercentage,0)<>0                               
                          
                          
-- hari included for service booking invoices which are credit invoices                                
UniOn All                                
                                
Select                                 
 serinvhcompanyid, serinvhshopid, serinvhdate, serinvhcAshacc,                                 
 COnvert(numeric(18,9), serinvhamount), COnvert(numeric(18,9),                             
 serinvhamount*seinvhdepexrate),                                
 COnvert(numeric(18,9), serinvhamount * serinvhcmpexrate), 0 , 'sbi',                                 
 serinvhdepartmentid  ,0 as PdChqCancelled                             
,ISNULL(serinvhuserid,0) as UserID                             
,isnull(serinvhTaxPercentage,0) as taxperc                           
,COnvert(numeric(18,9), isnull(serinvhTaxamount,0)) as taxamnt                         
,COnvert(numeric(18,9), isnull(serinvhTaxamount,0)* seinvhdepexrate) as Dtaxamnt                          
,COnvert(numeric(18,9), isnull(serinvhTaxamount,0)* serinvhcmpexrate) as Ctaxamnt,serinvno ,ISNULL(serinvhTaxCateID,0)                                  
From                                 
 losserviceinvheader                                 
Where                                 
 serinvhcancelled = 0 And                                 
 serinvhamount>0 And serinvhcAshacc Is null                            
-- and isnull(serinvhTaxPercentage,0)<>0                                  
                                      
UniOn All                    
                  
--Hire purchase                  
sELECT hprhCompanyID,hprhShopid,hprhREceiptDate,0 as serinvhcAshacc,                  
hprhReceiptAmount amount,                                    
hprhReceiptAmount * 1 damount,hprhReceiptAmount * 1 camount,0,                                    
'HP Receipt' Trans,hpDepartmentID ,0 as PdChqCancelled,                                    
rh.hprhUsed ,isnull(hpqhServTaxPerc,0)TaxPerc,                  
hprhReceiptAmount*(isnull(hpqhServTaxPerc,0)/100)TaxAmount,hprhReceiptAmount*(isnull(hpqhServTaxPerc,0)/100)TaxAmount,hprhReceiptAmount*(isnull(hpqhServTaxPerc,0)/100)TaxAmount,hpqhQuotationNo                  
 ,isnull(hpqhServTaxCateId,0)TaxCateId                               
FROM loshpReceiptHeader rh,loshpCustomerDetails c,                                    
ashops sh,adepartmentmaster ad,acurrencymaster cu                  
,losHpReceiptDetail rd                  
,losHpInvoiceHeader ih                                      
WHERE hprhCancel=0 AND rh.hprhCustomerid=c.hpCustID AND rh.hprhCompanyid=c.hpCompanyID AND                                    
sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and                                       
hprhShopid=sh.Shopid                   
and rd.hprdReceiptID=rh.hprhReceiptID and rd.hprdShopId=rh.hprhShopID                   
and rd.hprdInvoiceID=ih.hpqhQuotationID and rd.hprdShopId=ih.hpqhShopID                    
GO

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

/****** Object:  View [dbo].[vwHqprePurchaseOrder]    Script Date: 08/26/2011 16:57:14 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqprePurchaseOrder]'))
DROP VIEW [dbo].[vwHqprePurchaseOrder]
GO

USE [adminv2]
GO

/****** Object:  View [dbo].[vwHqprePurchaseOrder]    Script Date: 08/26/2011 16:57:14 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

------------------------------------------------------------------------------    
--Created By    :- Benzigar S D    
--Created Date  :- 09092008    
------------------------------------------------------------------------------    
--Modified By : Sreejith    
--Modified on : 20101108    
--Comment : added tow fields : pohSingleItemCatChecked,pohSingleItemCatId    
--select * from vwHqprePurchaseOrder  
------------------------------------------------------------------------------    
--RefNo			: RefNo-01                    
--Modified By	: MANUNADH.U                   
--Modified Date : 26/08/2011                    
--Purpose		: Add packingtypename to show in Pre-PurchaseOrder Prvw Report
------------------------------------------------------------------------------
--RefNo			: RefNo-02
--Modified By	: SHINE DAS                   
--Modified Date : 06/08/2012                    
--Purpose		: Add userID to show in report
------------------------------------------------------------------------------
CREATE VIEW [dbo].[vwHqprePurchaseOrder] AS        
select h.pohPoid,h.pohpono,h.pohPodate,a.itemid,h.pohSupAddr,h.pohdeliveryaddr,h.pohRefNo,h.pohremarks,
  p.podDetailID,p.podQty,p.podUnitPrice,p.poddescription,s.vendorname,ac.address1,ac.address2,cur.Symbol,        
  v.packunitcode,vw.itemdescription,vw.code,vw.vendorid,h.pohshipmentmode,h.pohpaymentmode,         
  convert(varchar(250),h.pohDeliveryTerms)pohdeliveryterms, pohProjectStartDate,
  pohProjectEndDate, pohProjectOtherInfo, pohCustomDutyByCustomer, pohTransportation,pohcancel,
  pohSingleItemCatChecked,pohSingleItemCatId
  ,v.packingtypename ------------------<<RefNo-01>>
  ,pohuserid -----: RefNo-02
FROM loprepurchaseorderheader h,loprepurchaseorderdetail p,vwpackingtype v,aitem a,        
avendormaster s ,acompanymaster ac,aCurrencyMaster cur,vwvendorItemDescription vw        
where p.poditemid=a.itemid and p.podpackingtypeID=v.packingtypeid and a.unitsid=v.unitsid        
and h.pohpoid=p.podpoid and h.pohVendorID = s.VendorID and h.pohcompanyid = ac.CompanyID        
and  s.CurrencyID = Cur.CurrencyID and vw.itemid=a.itemid and (h.pohVendorID=vw.vendorid or vw.vendorid is null)      
    
    
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania Update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO
/****** Object:  View [dbo].[vwHqPurchaseOrder]    Script Date: 05/28/2011 13:06:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwHqPurchaseOrder]'))
BEGIN
DROP VIEW vwHqPurchaseOrder
END
GO
  
/*  
Altered By Sreejith  
Altered on 20100724  
Added the left outer join with the function [dbo].[fnHQPurchaseorder]()  
*/  
------------------------------------------  
--RefNo : 01  
--Modified By : VinothMurugan V.  
--Modified Date : 30/07/2010  
--Purpose : adding priority and type  
------------------------------------------  
--Altered by SReejith  
--Altered on 20100818  
--Added  h.pohvendorid and h.pohDepartmentid fileds into the view  
--Already there was a column for vendorid from vwvendorItemDescription(Will be null in the cases if item does'nt exist)  
--So Added  h.pohvendorid also into the view for using in the report rptPurchaseOrderVendorWiseDetail  
--------------------------------------------  
--Altered by Abhishek CS  
--Altered on 20100914  
--Added  vwitemdescription for item description  
---------------------------------------------------------  
--RefNo:02  
--Modified by : VinothMurugan V  
--Date    : 06/10/2010  
--purpose   : Adding Other Charge Amount for kooddoo  
---------------------------------------------------------  
--Modified By : Sreejith  
--Modified on : 20101105  
--Comment : added tow fields : pohcmpexrate,pohdepexrate,pohSingleItemCatChecked,pohSingleItemCatId  
---------------------------------------------------------  
--Modified By : Nidheesh P V  
--Modified on : 20101105  
--Comment : added podItemTaxPercentage,podItemTaxAmount,podItemTaxCategory 
---------------------------------------------------------  
--Ref.No.1
--Modified By : AADYAKUMAR.D.V  
--Modified on : 02/08/2012  
--Comment     : Wathaniya need to show Purchase Request Number in 
--              Purchase Order preview    
---------------------------------------------------------  
--Ref.No.2
--Modified By : Shine Das
--Modified on : 04/08/2012  
--Comment     : Wathaniya need to Purchase Requested Person in report.
-- So userid also added. 
---------------------------------------------------------  
create VIEW [dbo].[vwHqPurchaseOrder] AS  
select  distinct h.pohDepartmentid,h.pohtype,h.pohPoid,h.pohpono,h.pohPodate,a.itemid,h.pohSupAddr,
h.pohdeliveryaddr,h.pohRefNo,h.pohremarks,  
p.podDetailID,p.podQty,p.podUnitPrice,  
p.poddescription ,s.vendorname,dm.departmentname, apt.packingtypename,  
ac.address1,ac.address2,cur.Symbol,  
v.packunitcode,  
--vw.itemdescription,  
vwi.itemdescription,  
vw.code,vw.vendorid,h.pohshipmentmode,h.pohpaymentmode, h.pohvendorid,  
convert(varchar(250),h.pohDeliveryTerms)pohdeliveryterms, h.pohProjectStartDate,  
h.pohProjectEndDate, h.pohProjectOtherInfo,h.pohCustomDutyByCustomer,h.pohTransportation,h.pohcancel ,  
fn.PreviousPO as PreviousPurchaseorder,fn.SupplierName as PreviousSupplier,  
a.itemrate LastItemRate,lp.priority,lt.type,  
sum( o.POAmount) POAmount,h.pohcmpexrate,h.pohdepexrate,h.pohSingleItemCatChecked,h.pohSingleItemCatId,    --RefNo:02  
podItemTaxPercentage,podItemTaxAmount,podItemTaxCategory,Q.pohpono Quatation,PR.pohpono PurchaseRequest
,h.pohuserid  --Ref.No.2
FROM lopurchaseorderheader h
--Ref.No.1---START---
left outer join lopurchaseorderheader Q on Q.pohtype='Q' 
and Q.pohPoid=H.pohquotationid
and Q.pohdepartmentid=h.pohdepartmentid
left outer join lopurchaseorderheader PR on PR.pohtype='R' 
and PR.pohPoid=Q.pohquotationid
and PR.pohdepartmentid=Q.pohdepartmentid
--Ref.No.1----END----
------------------------------------------------RefNo:02
left outer JOIN  loPurchaseOrderOthCharge o ON
o.POorderID  = h.pohPoid
----------------------------------------------
left outer join lostype as lt on lt.Typeid=h.pohTypeid --RefNo : 01
left outer join  lospriority lp on h.pohpriorityid = lp.priorityid --RefNo : 01
left outer join adepartmentmaster dm on  h.pohrequestdepartment=dm.departmentid
,vwpackingtype v,aitem a,apackingtype apt, vwItemDescription vwi,
avendormaster s ,acompanymaster ac,aCurrencyMaster cur,vwvendorItemDescription vw ,lopurchaseorderdetail p
left outer join [dbo].[fnHQPurchaseorder]() as Fn on itemid= p.poditemid and PurReqNo= p.podpoid
where p.poditemid=a.itemid and p.podpackingtypeID=v.packingtypeid and a.unitsid=v.unitsid
and h.pohpoid=p.podpoid and h.pohVendorID = s.VendorID and h.pohcompanyid = ac.CompanyID and p.podpackingtypeid=apt.packingtypeid  
and  s.CurrencyID = Cur.CurrencyID and vw.itemid=a.itemid and (h.pohVendorID=vw.vendorid or vw.vendorid is null)
and a.itemid=vwi.ItemID
-----------------------------------------------------------RefNo:02
group by
h.pohDepartmentid,h.pohtype,h.pohPoid,h.pohpono, h.pohPodate,a.itemid,h.pohSupAddr,
h.pohdeliveryaddr, h.pohRefNo , h.pohremarks,p.podDetailID, p.podQty , p.podUnitPrice,
p.poddescription ,s.vendorname,dm.departmentname, apt.packingtypename,ac.address1,ac.address2,cur.Symbol,v.packunitcode,vwi.itemdescription,  
vw.code,vw.vendorid,h.pohshipmentmode,h.pohpaymentmode, h.pohvendorid,
h.pohdeliveryterms, h.pohProjectStartDate,  
h.pohProjectEndDate, h.pohProjectOtherInfo, h.pohCustomDutyByCustomer, h.pohTransportation,h.pohcancel ,  
fn.PreviousPO, fn.SupplierName,
a.itemrate,lp.priority,lt.type,h.pohcmpexrate,h.pohdepexrate,h.pohSingleItemCatChecked,h.pohSingleItemCatId
,podItemTaxPercentage,podItemTaxAmount,podItemTaxCategory
,Q.pohpono,PR.pohpono
,h.pohuserid  --Ref.No.2
---------------------------------------------------------  
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania Update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = N'dbo' AND TABLE_NAME = N'vwPopulateUserSignatures' 
)   DROP VIEW dbo.vwPopulateUserSignatures
GO
/*
Created By : Shine Das
Created On : 16.06.2012
Purpose	   : To show sognature in reports.	
Created By : jyothish
Created On : 18.08.2012
Purpose	   : level no added.
*/
create  view vwPopulateUserSignatures as      
select a.interfaceid,a.levelid,a.levelname,d.usersignature,d.UserID,      
b.transactionid,d.UserName,b.updatetime,Rejected ,LevelNo from aApprovalLevelMaster a      
Left join aApprovalStatus b on a.interfaceid=b.interfaceid and a.levelid=      
b.approvalstatuslevel inner join aApprovalUserGroupRights c on       
c.ApprovalRights = a.LevelID and a.InterfaceID =c.InterfaceID inner join      
aUsers d on d.UserGroupID = c.UsergroupID 

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania Update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = N'dbo' AND TABLE_NAME = N'vwHqPurchaseOrderpre' 
)   DROP VIEW dbo.vwHqPurchaseOrderpre
GO
  
/*  
Altered By Sreejith  
Altered on 20100724  
Added the left outer join with the function [dbo].[fnHQPurchaseorder]()  
*/  
------------------------------------------  
--RefNo : 01  
--Modified By : VinothMurugan V.  
--Modified Date : 30/07/2010  
--Purpose : adding priority and type  
------------------------------------------  
--Altered by SReejith  
--Altered on 20100818  
--Added  h.pohvendorid and h.pohDepartmentid fileds into the view  
--Already there was a column for vendorid from vwvendorItemDescription(Will be null in the cases if item does'nt exist)  
--So Added  h.pohvendorid also into the view for using in the report rptPurchaseOrderVendorWiseDetail  
--------------------------------------------  
--Altered by Abhishek CS  
--Altered on 20100914  
--Added  vwitemdescription for item description  
---------------------------------------------------------  
--RefNo:02  
--Modified by : VinothMurugan V  
--Date    : 06/10/2010  
--purpose   : Adding Other Charge Amount for kooddoo  
---------------------------------------------------------  
--Modified By : Sreejith  
--Modified on : 20101105  
--Comment : added tow fields : pohcmpexrate,pohdepexrate,pohSingleItemCatChecked,pohSingleItemCatId  
---------------------------------------------------------  
--Modified By : Nidheesh P V  
--Modified on : 20101105  
--Comment : added podItemTaxPercentage,podItemTaxAmount,podItemTaxCategory  
create VIEW [dbo].[vwHqPurchaseOrderpre] AS  
select  distinct h.pohDepartmentid, 'p'  as pohtype,h.pohPoid  , h.pohpono  , h.pohPodate  ,a.itemid, h.pohSupAddr ,  
h. pohdeliveryaddr, h.pohRefNo , h.pohremarks,  
p.podDetailID, p.  podQty  , p.  podUnitPrice  ,  
p.  poddescription ,s.vendorname,dm.departmentname, apt.packingtypename,  
ac.address1,ac.address2,cur.Symbol,  
v.packunitcode,  
--vw.itemdescription,  
vwi.itemdescription,  
vw.code,vw.vendorid,h.pohshipmentmode,h.pohpaymentmode, h.pohvendorid,  
convert(varchar(250),h.pohDeliveryTerms)pohdeliveryterms, pohProjectStartDate,  
pohProjectEndDate, pohProjectOtherInfo, pohCustomDutyByCustomer, pohTransportation,pohcancel ,  
fn.PreviousPO as PreviousPurchaseorder,fn.SupplierName as PreviousSupplier,  
a.itemrate LastItemRate,''  as priority,'' as type,  
sum( isnull(o.POAmount,0)) POAmount,pohcmpexrate,pohdepexrate,pohSingleItemCatChecked,pohSingleItemCatId,    --RefNo:02  
podItemTaxPercentage,0 as podItemTaxAmount,podItemTaxCategory  
FROM loprepurchaseorderheader h  
------------------------------------------------RefNo:02  
left outer JOIN  loPrePurchaseOrderOthCharge o ON  
o.POorderID  = h.pohPoid  
----------------------------------------------  
--left outer join lostype as lt on lt.Typeid=h.pohTypeid --RefNo : 01  
--left outer join  lospriority lp on h.pohpriorityid = lp.priorityid --RefNo : 01  
left outer join adepartmentmaster dm on  h.pohDepartmentid=dm.departmentid  
,vwpackingtype v,aitem a,apackingtype apt, vwItemDescription vwi,  
avendormaster s ,acompanymaster ac,aCurrencyMaster cur,vwvendorItemDescription vw ,loPrePurchaseOrderDetail p  
left outer join [dbo].[fnHQPurchaseorder]() as Fn on itemid= p.poditemid and PurReqNo= p.podpoid  
where p.poditemid=a.itemid and p.podpackingtypeID=v.packingtypeid and a.unitsid=v.unitsid  
and h.pohpoid=p.podpoid and h.pohVendorID = s.VendorID and h.pohcompanyid = ac.CompanyID and p.podpackingtypeid=apt.packingtypeid  
and  s.CurrencyID = Cur.CurrencyID and vw.itemid=a.itemid and (h.pohVendorID=vw.vendorid or vw.vendorid is null)  
and a.itemid=vwi.ItemID  
-----------------------------------------------------------RefNo:02  
group by  
h.pohDepartmentid,h.pohtype,h.pohPoid , h.pohpono  , h.pohPodate  ,a.itemid, h.pohSupAddr ,  
h. pohdeliveryaddr, h.pohRefNo , h.pohremarks,p.podDetailID, p.  podQty  , p.  podUnitPrice  ,  
p.  poddescription ,s.vendorname,dm.departmentname, apt.packingtypename,ac.address1,ac.address2,cur.Symbol,v.packunitcode,vwi.itemdescription,  
vw.code,vw.vendorid,h.pohshipmentmode,h.pohpaymentmode, h.pohvendorid,  
pohdeliveryterms, pohProjectStartDate,  
pohProjectEndDate, pohProjectOtherInfo, pohCustomDutyByCustomer, pohTransportation,pohcancel ,  
fn.PreviousPO, fn.SupplierName,  
a.itemrate,pohcmpexrate,pohdepexrate,pohSingleItemCatChecked,pohSingleItemCatId  
,podItemTaxPercentage,podItemTaxCategory  
---------------------------------------------------------


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = N'dbo' AND TABLE_NAME = N'vwPurchaseOrderVendorWisePre' 
)   DROP VIEW dbo.vwPurchaseOrderVendorWisePre
GO
----------------------------------------------------------------    
--Created By   : Jyothish.SR  
--Created Date : 20111213    
--Comment       : [vwPurchaseOrderVendorWise]is modifeied for pre-purchase reports    
----------------------------------------------------------------    
create view [dbo].[vwPurchaseOrderVendorWisePre] as    
select a.pohpoid,a.pohpono,a.pohpodate,b.vendorname,ac.CurrencyName,ac.Symbol,a.pohtype,case a.poHcancel    
when 1 then 'Yes' when 0 then 'No' end as Cancelled, a.pohvendorid,a.pohQuotationid,a.pohnosupwise,    
a.pohsupaddr,a.pohduedate,a.pohvalue,a.pohdeliveryaddr, a.pohremarks, case a.pohpogenerated when 1 then 'Yes'    
when 0 then 'No' end as PurchaseGenerated,case a.pohBillGenerated when 1 then'Yes' when 0 then 'No' end as BillGenerated,    
a.pohLCopened,a.pohDepartmentID,a.pohLCAccountID, a.pohpurchaseAccountID,a.pohLCDueon,a.pohLCAmount,a.pohLCRemarks,    
case a.pohposted when 1 then 'Yes' when 0 then 'No' end as Posted , a.pohVerified as pohquotconfirmed, a.pohpoonhold,    
a.pohvalue as purchaseAmount ,isnull(a.pohremarks,'') remarks,vwpo.ShopRequetNO as ShopRequetNO,vwpo.HQRequestNo as HQRequestNo,    
vwpo.QuotationNO as QuotationNo, 0 as pohPrePurchaseid,vwpo.PrePurchaseNO as PrePurchaseNo    
from loPrePurchaseOrderHeader a inner join  avendormaster b on  a.pohvendorid=b.VendorID    
left outer join vwPurchaseOrderTracking3 vwpo on a.pohpoid=vwpo.pohpoid    
--left outer join loPurchaseOrderHeader ab on a.pohquotationid=ab.pohpoid    
--left outer join purchsetracking vw on a.pohpoid=vw.pohquotationid    
left outer join acurrencymaster ac on b.CurrencyID=ac.CurrencyID    
inner join  vwPurchaseAmount c on  a.pohpoid=c.pohpoid   
--left join aHQPurchaseOrderStatus d on a.pohpoid =d.PoID    
--and d.StatusID in (select StatusID from aHQPurchaseOrderStatus where poid=a.pohpoid and statusdate    
--in (select max(statusdate) from aHQPurchaseOrderStatus where poid=a.pohpoid))where a.pohtype='P' and  
 where a.pohcancel=0  
  
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_134 
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE ADMINV2
GO
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = N'dbo' AND TABLE_NAME = N'vwinvoices' 
)   DROP VIEW dbo.vwinvoices
GO     
--Added the tables of rexporting to select in the transaction , inculded duedate field                                    
--Modified by  : Hariharan , Hariharan R                                    
--Modified Date  : 14/03/2004, 03/05/2004                                    
--Comments  : v3, included bonded customs duty calculations                                    
--   given specialinvoice chking                                    
--   : included sales person id selection in Simtec Service Invoices                                    
--   : Included ocd.IoAmount for grouping invoice query                                    
--------------------------------------------------------------------------------------                                    
--Modified on :-17-08-09                                
--Modified by :Nidheesh                                 
--comments: added the condition ihNoofOCDetails=0 in the case of special inv to avoid RBD                                
----------------------------------------------------------------------------------------                            
--Modified on :13-11-09                                
--Modified by :Benzigar S D                                 
--comments: Modified Credit invoice other charges taking part                            
--        : If there is mor than one other charges then the same no of rows came in view.                            
--        : Here we need to take sum(other charges)                                    
----------------------------------------------------------------------------------------                             
--Modified on :20-03-10                                   
--Modified by :Nidheesh P V                                     
--comments: added Fine Invocie type ---                              
----------------------------------------------------------------------------------------                   
--Modified on :10-04-10                                   
--Modified by :Sreejith G A                                    
--comments: added the condition of checking 'fhInvoiceCancelled' bit in aFineheader table                  
--Purpose : to check if the main Invoice is deleted or not.                   
--   if deleted the bit 'fhInvoiceCancelled' in aFineHeader table becomes 1                            
----------------------------------------------------------------------------------------                              
--Modified on :21-04-10                                       
--Modified by :Sreejith G A                                   
--comments: Corrected the field service due date in SBI type. Initially it used Invoice date as due date                                   
----------------------------------------------------------------------------------------                     
--Modified on :29-11-10                                       
--Modified by :jyothish                           
--comments: FandB Invoice  is added             
----------------------------------------------------------------------------------------               
--Modified on :22-11-2011                                       
--Modified by :AADYA KUMAR.D.V                                   
--comments    :Added Tax in Account Service invoice            
--Ref.No      :1                                   
----------------------------------------------------------------------------------------          
--Modified on :30-11-2011                                       
--Modified by :MANUNADH. U      
--comments    :Added Tax in Shop Service invoice            
--Ref.No      :<<Ref.No2>>                                   
----------------------------------------------------------------------------------------                                     
--Modified on :11-02-2012                                             
--Modified by :JYOTHISH          
--comments    : commets condition in service invoice       
---Reason: negative invoice is entered in bb client         
 --Ref.No      :<<Ref.No3>>                                        
----------------------------------------------------------------------------------------                                          
--Ref.No.4            
--Modified on :18-02-2012                  
--Modified by :BIJESH.B      
--Ticket id   :FGJ-870028      
--Comment     :Added Tax in service invoice        
----------------------------------------------------------------------------------------          
--Ref.No.5           
--Modified on :29-02-2012                  
--Modified by :AADYA KUMAR.D.V      
--Ticket id   :FGY-413407      
--Comment     :Added new column TaxAmount        
----------------------------------------------------------------------------------------
--Ref.No.6
--Modified on :28-04-2012                  
--Modified by :SHINE DAS
--Ticket id   :EBD-440615    
--Comment     :Interface ID given for Credit Sales was wrong.        
----------------------------------------------------------------------------------------                 
CREATE VIEW [dbo].[vwinvoices] as                                           
SELECT AIH.CompanyID, 0 shopid, AIH.DepartmentID, AIH.InvoiceID, AIH.customerid,AIH.invoicedate,             
 AIH.invoiceno,isnull(aih.Referenceno,'') Referenceno,aih.remarks,            
 isnull(sum(ServiceQty * Amount),0)-isnull(AIH.Discount,0)+isnull(AIH.TaxAmount,0) as InvAmt--Ref.No:1                  
 ,'0 - 30' as Due,'AI' AS Type ,'Trade Debtors' Debtortype,aih.updatetime, CustomerCategory,                                           
 dateadd(dd,isnull(aih.DuePeriod,0),aih.invoicedate) duedate,Avg(aih.depexrate) as depexrate,            
 5007 InterFaceID, 0 SalesPersonID,c.CustomerType,0.0 DutyAmt,0.0 CostPrice ,CustGroupName,    
 isnull(AIH.TaxAmount,0) TaxAmount --Ref.No.5                    
FROM acustomermaster c, AccountsInvoiceHeader AIH                                          
 Left outer join ServiceInvoiceDetails SID on AIH.InvoiceID = SID.InvoiceID and             
 AIH.CompanyID = SID.CompanyID                                           
WHERE c.customerid = aih.customerid and AIH.CashInvoice = 0 and AIH.Proforma = 0 and                                           
  AIH.Cancelled = 0 and (datediff(dd,aIH.InvoiceDate,getdate())  between 0 and 30)                                            
group by AIH.CompanyID, AIH.InvoiceID, AIH.customerid, AIH.DepartmentID,AIH.invoicedate,AIH.invoiceno,            
  aih.referenceno, aih.remarks,aih.updatetime,AIH.Discount, customercategory, aih.dueperiod,             
  c.CustomerType ,CustGroupName,AIH.TaxAmount--Ref.No:1                                       
--having isnull(sum(ServiceQty * Amount),0) - isnull(AIH.Discount,0) >0.0  Ref.No3                                        
                                          
UNION all                                      
                               
SELECT AIH.CompanyID, 0 shopid, AIH.DepartmentID, AIH.InvoiceID,AIH.customerid,AIH.invoicedate,            
 AIH.invoiceno, isnull(aih.Referenceno,'') Referenceno, aih.remarks,                                           
 isnull(sum(ServiceQty * Amount),0)-isnull(AIH.Discount,0)+isnull(AIH.TaxAmount,0) as InvAmt,--Ref.No:1                                            
 '31 - 60' as Due,'AI' AS Type ,'Trade Debtors' Debtortype,aih.updatetime,CustomerCategory,            
 dateadd(dd,isnull(aih.DuePeriod,0),aih.invoicedate) duedate,Avg(aih.depexrate) as depexrate,            
 5007 InterFaceID, 0 SalesPersonID,c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
 isnull(AIH.TaxAmount,0) TaxAmount  --Ref.No.5                                          
FROM acustomermaster c, AccountsInvoiceHeader AIH                                          
 Left outer join ServiceInvoiceDetails SID on AIH.InvoiceID = SID.InvoiceID and             
 AIH.CompanyID = SID.CompanyID                               
WHERE c.customerid = aih.customerid and AIH.CashInvoice = 0 and AIH.Proforma = 0 and                                           
  AIH.Cancelled = 0 and (datediff(dd,aIH.InvoiceDate,getdate())  between 31 and 60)                                           
group by AIH.CompanyID, AIH.InvoiceID, AIH.customerid, AIH.DepartmentID,AIH.invoicedate,AIH.invoiceno,            
  aih.referenceno,aih.remarks,aih.updatetime,AIH.Discount,customercategory,aih.dueperiod,c.CustomerType,            
  CustGroupName ,AIH.TaxAmount--Ref.No:1                                         
--having isnull(sum(ServiceQty * Amount),0) - isnull(AIH.Discount,0) >0.0  Ref.No3                      
                              
union all                                          
                                          
SELECT AIH.CompanyID, 0 shopid, AIH.DepartmentID, AIH.InvoiceID, AIH.customerid,AIH.invoicedate,            
 AIH.invoiceno, isnull(aih.Referenceno,'') Referenceno, aih.remarks,            
 isnull(sum(ServiceQty * Amount),0)-isnull(AIH.Discount,0)+isnull(AIH.TaxAmount,0) as InvAmt,--Ref.No:1                                            
 '61 - 90' as Due  , 'AI' AS Type ,'Trade Debtors' Debtortype,aih.updatetime, customercategory,                                           
 dateadd(dd,isnull(aih.DuePeriod,0),aih.invoicedate) duedate,Avg(aih.depexrate) as depexrate,            
 5007 InterFaceID, 0 SalesPersonID,c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
 isnull(AIH.TaxAmount,0) TaxAmount --Ref.No.5                                         
FROM acustomermaster c, AccountsInvoiceHeader AIH                                          
  Left outer join ServiceInvoiceDetails SID on AIH.InvoiceID = SID.InvoiceID and             
  AIH.CompanyID = SID.CompanyID           
WHERE c.customerid = aih.customerid and AIH.CashInvoice = 0 and AIH.Proforma = 0 and                                           
  AIH.Cancelled = 0 and (datediff(dd,aIH.InvoiceDate,getdate())  between 61 and 90)                                            
group by AIH.CompanyID, AIH.InvoiceID, AIH.customerid, AIH.DepartmentID,AIH.invoicedate,AIH.invoiceno,            
  aih.referenceno, aih.remarks,aih.updatetime,AIH.Discount,customercategory,aih.dueperiod,            
  c.CustomerType,CustGroupName,AIH.TaxAmount--Ref.No:1                                          
--having isnull(sum(ServiceQty * Amount),0) - isnull(AIH.Discount,0) >0.0  Ref.No3                                        
                                          
union all                                          
                                          
SELECT AIH.CompanyID, 0 shopid, AIH.DepartmentID, AIH.InvoiceID,AIH.customerid,AIH.invoicedate,            
 AIH.invoiceno, isnull(aih.Referenceno,'') Referenceno, aih.remarks,            
 isnull(sum(ServiceQty * Amount),0)-isnull(AIH.Discount,0)+isnull(AIH.TaxAmount,0) as InvAmt,--Ref.No:1                                            
 ' > 90' as Due  , 'AI' AS Type ,'Trade Debtors' Debtortype,aih.updatetime, customercategory,                                           
 dateadd(dd,isnull(aih.DuePeriod,0),aih.invoicedate) duedate,Avg(aih.depexrate) as depexrate,            
 5007 InterFaceID, 0 SalesPersonID,c.CustomerType, 0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
 isnull(AIH.TaxAmount,0) TaxAmount --Ref.No.5     
FROM acustomermaster c, AccountsInvoiceHeader AIH                            
  Left outer join ServiceInvoiceDetails SID on AIH.InvoiceID = SID.InvoiceID and             
  AIH.CompanyID = SID.CompanyID                                           
WHERE c.customerid = aih.customerid and AIH.CashInvoice = 0 and AIH.Proforma = 0 and                                           
  AIH.Cancelled = 0 and (datediff(dd,aIH.InvoiceDate,getdate())>90)                                            
group by AIH.CompanyID, AIH.InvoiceID, AIH.customerid, AIH.DepartmentID, AIH.invoicedate,AIH.invoiceno,            
  aih.referenceno, aih.remarks,aih.updatetime,AIH.Discount,customercategory, aih.dueperiod,             
  c.CustomerType ,CustGroupName,AIH.TaxAmount--Ref.No:1                                         
--having isnull(sum(ServiceQty * Amount),0) - isnull(AIH.Discount,0) >0.0    Ref.No3                                      
                                          
union all                                          
                                          
--2. SHOP SERVICE INVOICE                                           
SELECT AIH.aiCompanyID, aih.aishopid, AIH.aiDepartmentID, AIH.aiInvoiceID, AIH.aicustomerid,                                           
  AIH.aiinvoicedate,AIH.aiinvoiceno, isnull(aih.aiReferenceno,'') Referenceno,aih.airemarks,      
  Case convert(int, isnull(aiCashPaidByShop,0)) when 0 then                                           
  (sum(siServiceQty * siAmount)) -isnull(AIH.aiDiscount,0) + ISNULL(AIH.aiTaxAmount,0) else  --<<Ref.No2>>                                         
  (sum((siServiceQty * siAmount) + siClearingCommAmt) ) -isnull(AIH.aiDiscount,0)             
  + ISNULL(AIH.aiTaxAmount,0) end as InvAmt, --<<Ref.No2>>                                          
  '0 - 30' as Due  , 'PSI' as type,'Trade Debtors' Debtortype, aih.updatetime, customercategory,                                           
  dateadd(dd,isnull(aih.aiDuePeriod,0), aih.aiinvoicedate) duedate,Avg(aih.aidepexrate) as depexrate,            
  1516 InterFaceID, 0 SalesPersonID,c.CustomerType,0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
  ISNULL(AIH.aiTaxAmount,0) TaxAmount --Ref.No.5                                        
FROM ashops s, acustomermaster c, losAccountsInvoiceHeader AIH                                          
  Left outer join losServiceInvoiceDetails SID on AIH.aiInvoiceID = SID.siInvoiceID and             
  AIH.aiCompanyID = SID.siCompanyID and aih.aishopid=sid.sishopid                                          
WHERE s.shopid = aih.aishopid and s.accountable is not null and c.customerid = aih.aicustomerid and             
  AIH.aiCashInvoice = 0 and AIH.aiProforma = 0 and AIH.aiCancelled = 0                                          
  and (datediff(dd,AIH.aiInvoiceDate,getdate()) between 0 and 30)                                            
GROUP BY AIH.aiCompanyID, AIH.AISHOPID, AIH.aiInvoiceID , AIH.aicustomerid, AIH.aiDepartmentID,                                           
  AIH.aiinvoicedate, aih.updatetime,AIH.aiinvoiceno, aih.aiReferenceno, aih.airemarks,AIH.aiDiscount,            
  customercategory, aih.aidueperiod,c.CustomerType,CustGroupName,AIH.aiTaxAmount,--<<Ref.No2>>            
  convert(int, isnull(aiCashPaidByShop,0))                                          
having sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) >0.0                                          
            
union all                                          
                                          
SELECT AIH.aiCompanyID, aih.aishopid, AIH.aiDepartmentID, AIH.aiInvoiceID, AIH.aicustomerid,                                           
  AIH.aiinvoicedate,AIH.aiinvoiceno, isnull(aih.aiReferenceno,'') Referenceno,aih.airemarks,                                           
  Case convert(int, isnull(aiCashPaidByShop,0)) when 0 then                                           
  (sum(siServiceQty * siAmount)) -isnull(AIH.aiDiscount,0) + ISNULL(AIH.aiTaxAmount,0) else   --<<Ref.No2>>                                        
  (sum((siServiceQty * siAmount) + siClearingCommAmt) ) -isnull(AIH.aiDiscount,0)            
  + ISNULL(AIH.aiTaxAmount,0) end as InvAmt,   --<<Ref.No2>>                                        
  '31 - 60' as Due  , 'PSI' as type,'Trade Debtors' Debtortype, aih.updatetime,customercategory,            
  dateadd(dd,isnull(aih.aiDuePeriod,0), aih.aiinvoicedate) duedate,Avg(aih.aidepexrate) as depexrate,            
  1516 InterFaceID, 0 SalesPersonID,c.CustomerType, 0.0 DutyAmt,0.0 CostPrice ,CustGroupName,    
  ISNULL(AIH.aiTaxAmount,0) TaxAmount  --Ref.No.5                                         
FROM ashops s, acustomermaster c, losAccountsInvoiceHeader AIH                                          
  Left outer join losServiceInvoiceDetails SID on AIH.aiInvoiceID = SID.siInvoiceID and             
  AIH.aiCompanyID = SID.siCompanyID and aih.aishopid=sid.sishopid                                          
WHERE s.shopid = aih.aishopid and s.accountable is not null and c.customerid = aih.aicustomerid and             
  AIH.aiCashInvoice = 0 and AIH.aiProforma = 0 and AIH.aiCancelled = 0 and             
  (datediff(dd,AIH.aiInvoiceDate,getdate()) between 31 and 60)                                            
GROUP BY AIH.aiCompanyID,AIH.AISHOPID,AIH.aiInvoiceID,AIH.aicustomerid,AIH.aiDepartmentID,                                           
  AIH.aiinvoicedate, aih.updatetime,AIH.aiinvoiceno, aih.aiReferenceno, aih.airemarks,                                           
  AIH.aiDiscount, customercategory, aih.aidueperiod,c.CustomerType,CustGroupName,                                           
  convert(int, isnull(aiCashPaidByShop,0)) ,AIH.aiTaxAmount--<<Ref.No2>>            
having sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) >0.0                                          
            
union all                                          
                                          
SELECT AIH.aiCompanyID, aih.aishopid, AIH.aiDepartmentID, AIH.aiInvoiceID, AIH.aicustomerid,                                           
  AIH.aiinvoicedate, AIH.aiinvoiceno, isnull(aih.aiReferenceno,'') Referenceno,aih.airemarks,                                           
  Case convert(int, isnull(aiCashPaidByShop,0)) when 0 then          
  (sum(siServiceQty * siAmount)) -isnull(AIH.aiDiscount,0) + ISNULL(AIH.aiTaxAmount,0)else --<<Ref.No2>>                                          
  (sum((siServiceQty * siAmount) + siClearingCommAmt) ) -isnull(AIH.aiDiscount,0)             
  + ISNULL(AIH.aiTaxAmount,0)end as InvAmt,   --<<Ref.No2>>                                         
  '61 - 90'  as Due  , 'PSI' as type,'Trade Debtors' Debtortype, aih.updatetime,customercategory,             
  dateadd(dd,isnull(aih.aiDuePeriod,0), aih.aiinvoicedate) duedate,Avg(aih.aidepexrate) as depexrate,            
  1516 InterFaceID, 0 SalesPersonID,c.CustomerType, 0.0 DutyAmt,0.0 CostPrice ,CustGroupName,    
  ISNULL(AIH.aiTaxAmount,0) TaxAmount --Ref.No.5                                           
FROM ashops s, acustomermaster c, losAccountsInvoiceHeader AIH                                          
  Left outer join losServiceInvoiceDetails SID on AIH.aiInvoiceID = SID.siInvoiceID and             
    AIH.aiCompanyID = SID.siCompanyID and aih.aishopid=sid.sishopid                                          
WHERE s.shopid = aih.aishopid and s.accountable is not null and c.customerid = aih.aicustomerid and            
  AIH.aiCashInvoice = 0 and AIH.aiProforma = 0 and AIH.aiCancelled = 0 and             
  (datediff(dd,AIH.aiInvoiceDate,getdate()) between 61 and 90)                                            
GROUP BY AIH.aiCompanyID, AIH.AISHOPID, AIH.aiInvoiceID,AIH.aicustomerid,AIH.aiDepartmentID,                                           
  AIH.aiinvoicedate, aih.updatetime,AIH.aiinvoiceno,aih.aiReferenceno,aih.airemarks,AIH.aiDiscount,            
  customercategory,aih.aidueperiod,c.CustomerType,CustGroupName,convert(int,             
  isnull(aiCashPaidByShop,0)),AIH.aiTaxAmount            
having sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) >0.0                                          
            
union all                                          
      
 --Ref.No.4  added " + ISNULL(AIH.aiTaxAmount,0) " in below query      
SELECT AIH.aiCompanyID,aih.aishopid,AIH.aiDepartmentID,AIH.aiInvoiceID, AIH.aicustomerid,                                           
  AIH.aiinvoicedate,AIH.aiinvoiceno,isnull(aih.aiReferenceno,'') Referenceno,aih.airemarks,                                
  Case convert(int, isnull(aiCashPaidByShop,0)) when 0 then                                           
  (sum(siServiceQty * siAmount)) -isnull(AIH.aiDiscount,0)       
  + ISNULL(AIH.aiTaxAmount,0) --Ref.No.4      
  else                                           
  (sum((siServiceQty * siAmount) + siClearingCommAmt) ) -isnull(AIH.aiDiscount,0)      
  + ISNULL(AIH.aiTaxAmount,0) --Ref.No.4      
   end as InvAmt,                                           
  ' > 90' as Due  , 'PSI' as type,'Trade Debtors' Debtortype, aih.updatetime,customercategory,             
  dateadd(dd,isnull(aih.aiDuePeriod,0), aih.aiinvoicedate) duedate,Avg(aih.aidepexrate) as depexrate,            
  1516 InterFaceID, 0 SalesPersonID,c.CustomerType, 0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
  ISNULL(AIH.aiTaxAmount,0) TaxAmount --Ref.No.5     
FROM ashops s, acustomermaster c, losAccountsInvoiceHeader AIH                                          
  Left outer join losServiceInvoiceDetails SID on AIH.aiInvoiceID = SID.siInvoiceID and             
  AIH.aiCompanyID = SID.siCompanyID and aih.aishopid=sid.sishopid                                          
WHERE s.shopid = aih.aishopid and s.accountable is not null and c.customerid = aih.aicustomerid and             
  AIH.aiCashInvoice = 0 and AIH.aiProforma = 0 and AIH.aiCancelled = 0 and                                           
  (datediff(dd,AIH.aiInvoiceDate,getdate()) > 90)                                            
GROUP BY AIH.aiCompanyID,AIH.AISHOPID,AIH.aiInvoiceID,AIH.aicustomerid,AIH.aiDepartmentID,            
  AIH.aiinvoicedate,aih.updatetime,AIH.aiinvoiceno, aih.aiReferenceno, aih.airemarks, AIH.aiDiscount,                                           
  customercategory,aih.aidueperiod,c.CustomerType,CustGroupName,convert(int, isnull(aiCashPaidByShop,0))                                          
  ,isnull(AIH.aiTaxAmount,0)  --Ref.No.4      
having sum(isnull(siServiceQty * siAmount,0))-isnull(AIH.aiDiscount,0) >0.0                                          
                                          
union all                                          
              
--3. SHOP CREDIT INVOICE                                          
--isnull(sum(idunitprice),0) as InvAmt                                          
SELECT IH.IHCompanyID, ih.IHshopid,IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,                                           
 IH.ihinvoicedate, iH.ihinvoiceno, isnull(ih.ihReferenceNo,'') Referenceno, ih.ihremarks,                                          
 case when s.futurevarchar ='B' and ih.ihdutypaidby='' then                                           
 (sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0))+isnull(sum(sid.idcdcustcur),0)                                          
 else (sum(isnull(SID.idunitprice,0))+ isnull(ocd.ioAmount,0))  end invAmt,             
 '0 - 30' as Due,'PCI' as type,'Trade Debtors' Debtortype,ih.updatetime, customercategory,             
 --ih.ihDueDate duedate,avg(ih.ihdepexrate) as depExRate,1527 InterfaceID,       --Ref.No.6
  ih.ihDueDate duedate,avg(ih.ihdepexrate) as depExRate,1504 InterfaceID,        --Ref.No.6
 ih.ihsalespersonid SalesPersonID,c.CustomerType, sum(isnull(sid.idcdcustcur,0)) DutyAmt,                                          
 sum(isnull(idQuantity*idcostprice,0.0)) CostPrice  ,CustGroupName,    
    SUM(ISNULL(idItemTaxAmount,0)) TaxAmount --Ref.No.5                                       
FROM ashops s, acustomermaster c, losInvoiceHeader IH                                          
  Left outer join losInvoiceDetail SID on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid                                          
  left outer join (            
 select ioShopID,ioInvoiceID,sum(ioAmount) ioAmount from losInvoiceOC                                           
 group by ioShopID,ioInvoiceID) ocd on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID                                          
WHERE s.shopid = ih.ihshopid and s.accountable is not null and ih.ihcustomerid = c.customerid and             
  IH.ihCashInvoice = 0 and IH.ihProforma = 0 and IH.ihCancelled = 0 and IH.ihtype = 'i'                                           
  and (datediff(dd,IH.ihInvoiceDate,getdate()) between 0 and 30)                                            
GROUP BY IH.ihCompanyID,IH.ihSHOPID,IH.ihInvoiceID,sID.idInvoiceID,IH.ihcustomerid,IH.ihDepartmentID,            
  IH.ihinvoicedate, ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo,ih.ihremarks, IH.ihDiscount,             
  customercategory, ih.ihDueDate ,IH.ihdutypaidby,s.futurevarchar, ih.ihsalespersonid, c.CustomerType,             
  ocd.ioAmount,CustGroupName    
                                       
            
UNION ALL                                          
--isnull(sum(idunitprice),0) as InvAmt                                          
SELECT IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID,IH.ihcustomerid,IH.ihinvoicedate,            
  iH.ihinvoiceno,isnull(ih.ihReferenceNo,'') Referenceno,ih.ihremarks,             
  case when  s.futurevarchar ='B' and ih.ihdutypaidby='' then                   
  sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0)+isnull(sum(sid.idcdcustcur),0)                                          
  else sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0) end invAmt, '31 - 60' as Due,'PCI' as type,            
  'Trade Debtors' Debtortype, ih.updatetime, customercategory,ih.ihDueDate duedate ,            
  --avg(ih.ihdepexrate) as depExRate,1527 InterfaceID,ih.ihsalespersonid SalesPersonID,c.CustomerType, --Ref.No.6
    avg(ih.ihdepexrate) as depExRate,1504 InterfaceID,ih.ihsalespersonid SalesPersonID,c.CustomerType, --Ref.No.6            
  sum(isnull(sid.idcdcustcur,0)) DutyAmt,sum(isnull(idQuantity*idcostprice,0.0)) CostPrice,CustGroupName,    
  SUM(ISNULL(idItemTaxAmount,0)) TaxAmount  --Ref.No.5                                         
FROM ashops s,acustomermaster c, losInvoiceHeader IH                                          
  Left outer join losInvoiceDetail SID on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid                                          
  left outer join (            
 select ioShopID,ioInvoiceID, sum (ioAmount) ioAmount from losInvoiceOC,losInvoiceHeader IH             
 where ioshopid=ih.ihshopid and ioinvoiceid=ih.ihinvoiceid group by ioShopID,ioInvoiceID) ocd                                          
 on ih.ihshopid = ocd.ioshopid and ih.ihinvoiceid = ocd.ioinvoiceid                                                   
WHERE s.shopid = ih.ihshopid and s.accountable is not null and ih.ihcustomerid = c.customerid and             
  IH.ihCashInvoice = 0 and IH.ihProforma = 0 and IH.ihCancelled = 0 and IH.ihtype = 'i'                                          
  and (datediff(dd,IH.ihInvoiceDate,getdate()) between 31 and 60)                                      
GROUP BY IH.ihCompanyID,IH.ihSHOPID,IH.ihInvoiceID,sID.idInvoiceID,IH.ihcustomerid,IH.ihDepartmentID,            
  IH.ihinvoicedate, ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo,ih.ihremarks, IH.ihDiscount,            
  customercategory,ih.ihDueDate,IH.ihdutypaidby,s.futurevarchar, ih.ihsalespersonid, c.CustomerType,             
  ocd.ioAmount ,CustGroupName    
                                       
                                          
UNION ALL                                          
--isnull(sum(idunitprice),0) as InvAmt,                                           
SELECT IH.IHCompanyID,ih.IHshopid,IH.IHDepartmentID,IH.IHInvoiceID,IH.ihcustomerid,IH.ihinvoicedate,            
  iH.ihinvoiceno,isnull(ih.ihReferenceNo,'') Referenceno,ih.ihremarks,            
  case when  s.futurevarchar ='B' and ih.ihdutypaidby='' then                                           
  sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0)+isnull(sum(sid.idcdcustcur),0)                                          
  else sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0)  end invAmt,'61 - 90' as Due  ,                                           
  'PCI' as type,'Trade Debtors' Debtortype, ih.updatetime, customercategory,ih.ihDueDate duedate ,            
  --avg(ih.ihdepexrate) as depExRate,1527 InterfaceID,ih.ihsalespersonid SalesPersonID,c.CustomerType, --Ref.No.6
    avg(ih.ihdepexrate) as depExRate,1504 InterfaceID,ih.ihsalespersonid SalesPersonID,c.CustomerType, --Ref.No.6           
  sum(isnull(sid.idcdcustcur,0)) DutyAmt,sum(isnull(idQuantity*idcostprice,0)) CostPrice,CustGroupName,    
  SUM(ISNULL(idItemTaxAmount,0)) TaxAmount   --Ref.No.5                                        
FROM ashops s, acustomermaster c, losInvoiceHeader IH                          
  Left outer join losInvoiceDetail SID on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid                                          
  left outer join (            
 select ioShopID,ioInvoiceID, sum (ioAmount) ioAmount from losInvoiceOC,losInvoiceHeader IH             
 where ioshopid=ih.ihshopid and ioinvoiceid=ih.ihinvoiceid group by ioShopID,ioInvoiceID) ocd                                          
   on ih.ihshopid = ocd.ioshopid and ih.ihinvoiceid = ocd.ioinvoiceid                 
WHERE s.shopid = ih.ihshopid and s.accountable is not null and ih.ihcustomerid = c.customerid and             
  IH.ihCashInvoice = 0 and IH.ihProforma = 0 and IH.ihCancelled = 0 and IH.ihtype = 'i'                                          
  and (datediff(dd,IH.ihInvoiceDate,getdate()) between 61 and 90)                                           
GROUP BY IH.ihCompanyID, IH.ihSHOPID,IH.ihInvoiceID,sID.idInvoiceID, IH.ihcustomerid,                                           
  IH.ihDepartmentID, IH.ihinvoicedate, ih.updatetime,iH.ihinvoiceno, ih.ihReferenceNo,                                           
  ih.ihremarks, IH.ihDiscount, customercategory, ih.ihDueDate ,IH.ihdutypaidby,                                          
  s.futurevarchar, ih.ihsalespersonid, c.CustomerType, ocd.ioAmount ,CustGroupName     
                                       
                               
UNION ALL                                            
--isnull(sum(idunitprice),0) as InvAmt,                                           
SELECT IH.IHCompanyID,ih.IHshopid,IH.IHDepartmentID,IH.IHInvoiceID,IH.ihcustomerid,IH.ihinvoicedate,            
  iH.ihinvoiceno,isnull(ih.ihReferenceNo,'') Referenceno,ih.ihremarks,            
  case when s.futurevarchar ='B' and ih.ihdutypaidby='' then                                           
  sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0)+isnull(sum(sid.idcdcustcur),0)                                          
  else sum(isnull(SID.idunitprice,0))+isnull(ocd.ioAmount,0) end invAmt,' > 90' as Due,'PCI' as type,            
  'Trade Debtors' Debtortype, ih.updatetime, customercategory,ih.ihDueDate duedate ,            
  --avg(ih.ihdepexrate) as depExRate,1527 InterfaceID,ih.ihsalespersonid SalesPersonID,c.CustomerType, --Ref.No.6
    avg(ih.ihdepexrate) as depExRate,1504 InterfaceID,ih.ihsalespersonid SalesPersonID,c.CustomerType, --Ref.No.6            
  sum(isnull(sid.idcdcustcur,0)) DutyAmt,sum(isnull(idQuantity*idcostprice,0)) CostPrice,CustGroupName,    
  SUM(ISNULL(idItemTaxAmount,0)) TaxAmount --Ref.No.5                                           
FROM ashops s, acustomermaster c, losInvoiceHeader IH                                          
  Left outer join losInvoiceDetail SID on IH.IHInvoiceID = SID.idInvoiceID and ih.IHshopid=sid.idshopid                                          
  left outer join (            
 select ioShopID,ioInvoiceID, sum (ioAmount) ioAmount from losInvoiceOC,losInvoiceHeader IH             
 where ioshopid=ih.ihshopid and ioinvoiceid=ih.ihinvoiceid group by ioShopID,ioInvoiceID) ocd                                          
   on ih.ihshopid = ocd.ioshopid and ih.ihinvoiceid = ocd.ioinvoiceid                                           
WHERE s.shopid = ih.ihshopid and s.accountable is not null and ih.ihcustomerid = c.customerid and             
  IH.ihCashInvoice = 0 and IH.ihProforma = 0 and IH.ihCancelled = 0 and IH.ihtype = 'i' and             
  (datediff(dd,IH.ihInvoiceDate,getdate()) > 90)              
GROUP BY IH.ihCompanyID,IH.ihSHOPID,IH.ihInvoiceID,sID.idInvoiceID,IH.ihcustomerid,IH.ihDepartmentID,            
  IH.ihinvoicedate,ih.updatetime,iH.ihinvoiceno,ih.ihReferenceNo,ih.ihremarks, IH.ihDiscount,             
  customercategory, ih.ihDueDate ,IH.ihdutypaidby,s.futurevarchar, ih.ihsalespersonid, c.CustomerType,             
  ocd.ioAmount,CustGroupName    
                                      
                                          
union all                                          
--4. SHOP SPECIAL INVOICE                                          
SELECT IH.IHCompanyID,ih.IHshopid,IH.IHDepartmentID,IH.IHInvoiceID,IH.ihcustomerid,IH.ihinvoicedate,            
  iH.ihinvoiceno,isnull(ih.IhReferenceNo,'') referenceno,ih.ihremarks,             
  isnull(sum(case when idratetype =1 then -idunitprice else idunitprice end),0) as InvAmt,                                           
  '0 - 30' as Due  , 'PDI' as type,'Trade Debtors' Debtortype, ih.updatetime,customercategory,             
  ih.IhDueDate duedate,avg(ih.ihdepexrate) as depExRate,5008 interfaceID,            
  ih.ihsalespersonid SalesPersonID,c.CustomerType,0.0 DutyAmt,                                          
  sum(isnull(idQuantity*idcostprice,0)) CostPrice ,CustGroupName,    
  SUM(ISNULL(idItemTaxAmount,0)) TaxAmount --Ref.No.5                                         
FROM ashops s, acustomermaster c, losSpecialInvoiceHeader IH                                        
  Left outer join losSpecialInvoiceDetail SID on IH.IHInvoiceID = SID.idInvoiceID and             
  ih.IHshopid=sid.idshopid and idratetype =0 and ihNoofOCDetails=0                                         
WHERE s.shopid = ih.ihshopid and s.accountable is not null and ih.ihcustomerid = c.customerid and             
  IH.ihCashInvoice = 0 and IH.ihProforma = 0 and IH.ihCancelled = 0 and             
  (datediff(dd,IH.ihInvoiceDate,getdate()) between 0 and 30) and ih.ihtransfinished=1                                          
GROUP BY IH.ihCompanyID, IH.ihSHOPID, IH.ihInvoiceID, IH.ihcustomerid, IH.ihinvoicedate,                                           
  ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo, ih.ihremarks,IH.ihDepartmentID, IH.ihDiscount,             
  customercategory, ih.IhDueDate,ih.ihsalespersonid,c.CustomerType  ,CustGroupName     
                                        
                                          
union all                                          
                                          
SELECT IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,                                           
  IH.ihinvoicedate,iH.ihinvoiceno,isnull(ih.IhReferenceNo,'') referenceno,ih.ihremarks,             
  isnull(sum(case when idratetype =1 then -idunitprice else idunitprice end),0) as InvAmt,             
  '31 - 60' as Due,'PDI' as type,'Trade Debtors' Debtortype, ih.updatetime, customercategory,                                           
  ih.IhDueDate duedate,avg(ih.ihdepexrate) as depExRate,5008 interfaceID,                                          
  ih.ihsalespersonid SalesPersonID,c.CustomerType,0.0 DutyAmt,                                          
  sum(isnull(idQuantity*idcostprice,0)) CostPrice ,CustGroupName,    
  SUM(ISNULL(idItemTaxAmount,0)) TaxAmount  --Ref.No.5                                  
FROM ashops s, acustomermaster c, losSpecialInvoiceHeader IH                                          
  Left outer join losSpecialInvoiceDetail SID on IH.IHInvoiceID = SID.idInvoiceID and             
  ih.IHshopid=sid.idshopid and idratetype =0 and ihNoofOCDetails=0                                         
WHERE s.shopid = ih.ihshopid and s.accountable is not null and ih.ihcustomerid = c.customerid and             
  IH.ihCashInvoice = 0 and IH.ihProforma = 0 and IH.ihCancelled = 0 and             
  (datediff(dd,IH.ihInvoiceDate,getdate()) between 31 and 60) and ih.ihtransfinished=1                                          
GROUP BY IH.ihCompanyID, IH.ihSHOPID, IH.ihInvoiceID, IH.ihcustomerid, IH.ihinvoicedate,                                           
 ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo, ih.ihremarks,IH.ihDepartmentID,                                           
 IH.ihDiscount, customercategory, ih.IhDueDate,ih.ihsalespersonid,c.CustomerType ,CustGroupName
                         
union all                                          
                                          
SELECT IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,                                           
  IH.ihinvoicedate,  iH.ihinvoiceno,  isnull(ih.IhReferenceNo,'') referenceno,ih.ihremarks,            
  isnull(sum(case when idratetype =1 then -idunitprice else idunitprice end),0) as InvAmt,             
  '61 - 90' as Due,'PDI' as type,'Trade Debtors' Debtortype, ih.updatetime, customercategory,                                           
  ih.IhDueDate duedate,avg(ih.ihdepexrate) as depExRate,5008 interfaceID,ih.ihsalespersonid,            
  c.CustomerType, 0.0 DutyAmt,sum(isnull(idQuantity*idcostprice,0)) CostPrice ,CustGroupName,    
  SUM(ISNULL(idItemTaxAmount,0)) TaxAmount   --Ref.No.5                                        
FROM ashops s, acustomermaster c, losSpecialInvoiceHeader IH                                          
  Left outer join losSpecialInvoiceDetail SID on IH.IHInvoiceID = SID.idInvoiceID and             
  ih.IHshopid=sid.idshopid and idratetype =0  and ihNoofOCDetails=0                                        
WHERE s.shopid = ih.ihshopid and s.accountable is not null and ih.ihcustomerid = c.customerid and             
  IH.ihCashInvoice = 0 and IH.ihProforma = 0 and IH.ihCancelled = 0 and             
  (datediff(dd,IH.ihInvoiceDate,getdate()) between 61 and 90) and ih.ihtransfinished=1                                          
GROUP BY IH.ihCompanyID, IH.ihSHOPID, IH.ihInvoiceID, IH.ihcustomerid, IH.ihinvoicedate,                                           
  ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo, ih.ihremarks, IH.ihDepartmentID, IH.ihDiscount,             
  customercategory, ih.IhDueDate,ih.ihsalespersonid,c.CustomerType ,CustGroupName 
                                          
union all                                          
                                          
SELECT IH.IHCompanyID, ih.IHshopid, IH.IHDepartmentID, IH.IHInvoiceID, IH.ihcustomerid,                                           
  IH.ihinvoicedate,  iH.ihinvoiceno,  isnull(ih.IhReferenceNo,'') referenceno, ih.ihremarks,             
  isnull(sum(case when idratetype =1 then -idunitprice else idunitprice end),0) as InvAmt,             
  ' > 90' as Due,'PDI' as type,'Trade Debtors' Debtortype, ih.updatetime, customercategory,                                           
  ih.IhDueDate duedate ,avg(ih.ihdepexrate) as depExRate,5008 interfaceID,                                          
  ih.ihsalespersonid SalesPersonID, c.CustomerType,0.0 DutyAmt,                                          
  sum(isnull(idQuantity*idcostprice,0)) CostPrice ,CustGroupName,    
  SUM(ISNULL(idItemTaxAmount,0)) TaxAmount  --Ref.No.5                                          
FROM ashops s, acustomermaster c, losSpecialInvoiceHeader IH                                          
  Left outer join losSpecialInvoiceDetail SID on IH.IHInvoiceID = SID.idInvoiceID and             
  ih.IHshopid=sid.idshopid and idratetype =0  and ihNoofOCDetails=0                                        
WHERE s.shopid = ih.ihshopid and s.accountable is not null and ih.ihcustomerid = c.customerid and             
  IH.ihCashInvoice = 0 and IH.ihProforma = 0 and IH.ihCancelled = 0 and             
  (datediff(dd,IH.ihInvoiceDate,getdate()) >90) and ih.ihtransfinished=1                                          
GROUP BY IH.ihCompanyID, IH.ihSHOPID, IH.ihInvoiceID, IH.ihcustomerid, IH.ihinvoicedate,                              
 ih.updatetime, iH.ihinvoiceno, ih.ihReferenceNo, ih.ihremarks,IH.ihDepartmentID,                                           
 IH.ihDiscount, customercategory, ih.IhDueDate,ih.ihsalespersonid,c.CustomerType  ,CustGroupName 
union all                                          
                                          
--5. debit note from hq                                          
                                          
SELECT dcn.DCNCompanyid, 0 shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNCustomerID,dcn.DCNDate,             
  dcn.DCNNo, isnull(dcn.DCNReferenceNo,'') referenceno, dcn.DCNDetails,DCNAmount as InvAmt,             
  '0 - 30'  as Due, 'DCN' as type,'Trade Debtors' Debtortype,dcn.updatetime, customercategory,             
  dcn.dcndate duedate,avg(dcn.dcndepexrate) as depExRate,5010 InterfaceID, 0 SalesPersonID,                                          
  c.CustomerType, 0.0 DutyAmt,0.0 CostPrice ,CustGroupName,    
  0.0 TaxAmount --Ref.No.5                                          
FROM acustomermaster c, debitcreditnote dcn                                          
WHERE dcn.dcncustomerid = c.customerid and dcn.DCNCustomerID is not null and dcn.DCNDebit =1 and             
  dcn.DCNCancelled= 0 and (datediff(dd,dcn.dcnDate,getdate()) between 0 and 30)                                          
GROUP BY dcn.dcncompanyid,dcn.dcnid,dcn.dcncustomerid,dcn.dcndate,dcn.updatetime,dcn.dcnno,            
  dcn.DCNReferenceNo, dcn.dcndetails,dcn.dcnDepartmentID, dcn.dcnamount,                                            
  customercategory,c.CustomerType  ,CustGroupName                                        
                                          
union all                                 
                                          
SELECT dcn.DCNCompanyid, 0 shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNCustomerID,                                           
  dcn.DCNDate,dcn.DCNNo, isnull(dcn.DCNReferenceNo,'') referenceno, dcn.DCNDetails,DCNAmount as InvAmt,            
  '31 - 60'  as Due, 'DCN' as type,'Trade Debtors' Debtortype,dcn.updatetime, customercategory ,             
  dcn.dcndate duedate,avg(dcn.dcndepexrate) as depExRate,5010 InterfaceID, 0 SalesPersonID,                                          
  c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
  0.0 TaxAmount  --Ref.No.5                                        
FROM acustomermaster c, debitcreditnote dcn                                          
WHERE c.customerid = dcn.dcncustomerid and dcn.DCNCustomerID is not null and dcn.DCNDebit =1 and             
  dcn.DCNCancelled= 0 and (datediff(dd,dcn.dcnDate,getdate()) between 31 and 60)                                          
GROUP BY dcn.dcncompanyid, dcn.dcnid, dcn.dcncustomerid, dcn.dcndate, dcn.updatetime,                                           
 dcn.dcnno, dcn.DCNReferenceNo, dcn.dcndetails,dcn.dcnDepartmentID, dcn.dcnamount,                                           
 customercategory, c.CustomerType  ,CustGroupName                                        
                                          
union all                                          
                                          
SELECT dcn.DCNCompanyid,0 shopid,dcn.dcndepartmentid,dcn.DCNId,dcn.DCNCustomerID,dcn.DCNDate,dcn.DCNNo,             
  isnull(dcn.DCNReferenceNo,'') referenceno, dcn.DCNDetails,DCNAmount as InvAmt,'61 - 90'  as Due,             
  'DCN' as type,'Trade Debtors' Debtortype,dcn.updatetime, customercategory , dcn.dcndate duedate,                                          
  avg(dcn.dcndepexrate) as depExRate,5010 InterfaceID, 0 SalesPersonID,                                          
  c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
  0.0 TaxAmount  --Ref.No.5                                        
FROM acustomermaster c, debitcreditnote dcn                                          
WHERE c.customerid = dcn.dcncustomerid and dcn.DCNCustomerID is not null and                                           
  dcn.DCNDebit =1 and dcn.DCNCancelled= 0 and (datediff(dd,dcn.dcnDate,getdate()) between 61 and 90)                                          
GROUP BY dcn.dcncompanyid, dcn.dcnid, dcn.dcncustomerid, dcn.dcndate, dcn.updatetime,                                           
  dcn.dcnno, dcn.DCNReferenceNo, dcn.dcndetails,dcn.dcnDepartmentID, dcn.dcnamount,                                           
  customercategory,c.CustomerType ,CustGroupName                                         
                                          
union all                                          
                                          
SELECT dcn.DCNCompanyid,0 shopid,dcn.dcndepartmentid,dcn.DCNId,dcn.DCNCustomerID,dcn.DCNDate,dcn.DCNNo,             
  isnull(dcn.DCNReferenceNo,'') referenceno, dcn.DCNDetails,DCNAmount as InvAmt,' > 90'  as Due,             
  'DCN' as type,'Trade Debtors' Debtortype,dcn.updatetime, customercategory, dcn.dcndate duedate,                                          
  avg(dcn.dcndepexrate) as depExRate,5010 InterfaceID, 0 SalesPersonID,                              
  c.CustomerType, 0.0 DutyAmt,0.0 CostPrice ,CustGroupName,    
  0.0 TaxAmount --Ref.No.5                                         
FROM acustomermaster c, debitcreditnote dcn                                          
WHERE c.customerid = dcn.dcncustomerid and dcn.DCNCustomerID is not null and dcn.DCNDebit =1 and             
  dcn.DCNCancelled= 0 and (datediff(dd,dcn.dcnDate,getdate()) > 90)                                           
GROUP BY dcn.dcncompanyid, dcn.dcnid, dcn.dcncustomerid, dcn.dcndate, dcn.updatetime,                                           
 dcn.dcnno, dcn.DCNReferenceNo, dcn.dcndetails,dcn.dcnDepartmentID, dcn.dcnamount,                                           
 customercategory, c.CustomerType,CustGroupName                                          
                                          
union all                                          
                                          
-- payment to customer considered as invoice                                          
select ph.phcompanyid, 0 shopid, ph.phdepartmentid, ph.phpaymentid, ph.phcustomerid,ph.phpaymentdate,              
  ph.phpaymentno, isnull(ph.phcbreferenceno,'') referenceno,ph.phremarks, ph.phcustomeramount,             
  '0 - 30' due,  'rf' type,'Other Debtors' Debtortype,ph.updatetime, customercategory,             
  ph.phpaymentdate duedate,ph.phdepexrate as depExRate,5005 InterfaceID, 0 SalesPersonID,                                       
  c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
  0.0 TaxAmount --Ref.No.5                                         
from acustomermaster c, ahqpaymentvoucherheader ph                                           
where c.customerid = ph.phcustomerid and ph.phcancelled =0 and phcustomerid is not null and                                           
 (getdate() - ph.phpaymentdate between 0 and 30)                                          
                                          
union all                          
                                          
select ph.phcompanyid, 0 shopid, ph.phdepartmentid, ph.phpaymentid, ph.phcustomerid,ph.phpaymentdate,              
  ph.phpaymentno, isnull(ph.phcbreferenceno,'') referenceno,ph.phremarks,  ph.phcustomeramount,             
  '31 - 60' due,  'rf' type,'Other Debtors' Debtortype, ph.updatetime, customercategory,             
  ph.phpaymentdate duedate,ph.phdepexrate as depExRate,5005 InterfaceID, 0 SalesPersonID,                                          
  c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
  0.0 TaxAmount --Ref.No.5                                         
from acustomermaster c, ahqpaymentvoucherheader ph                                           
where c.customerid = ph.phcustomerid and ph.phcancelled =0 and phcustomerid is not null and                                           
 (getdate() - ph.phpaymentdate between 31 and 60)                               
                                         
union all                                          
                              
select ph.phcompanyid, 0 shopid, ph.phdepartmentid, ph.phpaymentid, ph.phcustomerid,                                           
  ph.phpaymentdate,  ph.phpaymentno, isnull(ph.phcbreferenceno,'') referenceno,                                           
  ph.phremarks, ph.phcustomeramount, '61 - 90' due,  'rf' type,'Other Debtors' Debtortype,ph.updatetime,            
  customercategory, ph.phpaymentdate duedate,ph.phdepexrate as depExRate,5005 InterfaceID,             
  0 SalesPersonID,c.CustomerType, 0.0 DutyAmt,0.0 CostPrice ,CustGroupName,     
  0.0 TaxAmount  --Ref.No.5                            
from acustomermaster c, ahqpaymentvoucherheader ph                                           
where c.customerid = ph.phcustomerid and ph.phcancelled =0 and phcustomerid is not null and                                           
 (getdate() - ph.phpaymentdate between 61 and 90)                                           
                                          
union all                                          
                                          
select ph.phcompanyid, 0 shopid, ph.phdepartmentid, ph.phpaymentid, ph.phcustomerid,                                           
  ph.phpaymentdate,  ph.phpaymentno, isnull(ph.phcbreferenceno,'') referenceno,                             
  ph.phremarks, ph.phcustomeramount, ' > 90' due,  'rf' type,'Other Debtors' Debtortype,                                           
  ph.updatetime, customercategory, ph.phpaymentdate duedate,ph.phdepexrate as depExRate,5005 InterfaceID,            
  0 SalesPersonID,c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
  0.0 TaxAmount --Ref.No.5                                         
from acustomermaster c, ahqpaymentvoucherheader ph                                           
where c.customerid = ph.phcustomerid and ph.phcancelled =0 and phcustomerid is not null and                                           
 (getdate() - ph.phpaymentdate > 90)                                          
                                          
union all                                          
-- for booking service invoices hari 020319                                          
SELECT IH.CompanyID, ih.shopid, IH.serinvhdepartmentid,IH.invoiceid,IH.customerid,IH.invoicedate,             
  iH.invoiceno,isnull(ih.referenceno,''),ih.remarks,serinvhamount,'0 - 30' as Due,'SBI' as type,      'Trade Debtors' Debtortype, ih.serinvhupdatetime,customercategory, IH.serinvhduedate duedate,            
  ih.seinvhdepexrate as depExRate,1802 InterfaceID,  serinvhpreparedby SalesPersonID, c.CustomerType,             
  0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
  serinvhTaxamount TaxAmount  --Ref.No.5                                        
FROM ashops s, acustomermaster c,  vwbookingservinvoices IH                                           
where s.shopid = ih.shopid and s.accountable is not null and c.customerid = ih.customerid and                                          
 datediff(dd,IH.InvoiceDate,getdate()) between 0 and 30                                          
                                          
union all                                          
                                          
SELECT IH.CompanyID, ih.shopid, IH.serinvhdepartmentid, IH.invoiceid, IH.customerid,IH.invoicedate,             
  iH.invoiceno,isnull(ih.referenceno,''),ih.remarks,serinvhamount,'31 - 60' as Due,'SBI' as type,            
  'Trade Debtors' Debtortype,ih.serinvhupdatetime,customercategory, IH.serinvhduedate duedate,            
  ih.seinvhdepexrate as depExRate,1802 InterfaceID, serinvhpreparedby SalesPersonID, c.CustomerType,             
  0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
  serinvhTaxamount TaxAmount --Ref.No.5                                         
FROM ashops s, acustomermaster c, vwbookingservinvoices IH                                           
where s.shopid = ih.shopid and s.accountable is not null and c.customerid = ih.customerid and                                           
 datediff(dd,IH.InvoiceDate,getdate()) between 31 and 60                                          
                                          
union all                        
                                          
SELECT IH.CompanyID, ih.shopid, IH.serinvhdepartmentid, IH.invoiceid, IH.customerid,IH.invoicedate,             
  iH.invoiceno, isnull(ih.referenceno,''), ih.remarks, serinvhamount,'61 - 90' as Due,'SBI' as type,            
  'Trade Debtors' Debtortype, ih.serinvhupdatetime,customercategory, IH.serinvhduedate duedate,            
  ih.seinvhdepexrate as depExRate,1802 InterfaceID, serinvhpreparedby SalesPersonID, c.CustomerType,            
  0.0 DutyAmt,0.0 CostPrice ,CustGroupName,    
  serinvhTaxamount TaxAmount --Ref.No.5                                         
FROM ashops s, acustomermaster c, vwbookingservinvoices IH             
where s.shopid = ih.shopid and s.accountable is not null and                                           
 c.customerid = ih.customerid and datediff(dd,IH.InvoiceDate,getdate()) between 61 and 90                                          
                                          
union all                                          
                                          
SELECT IH.CompanyID, ih.shopid, IH.serinvhdepartmentid, IH.invoiceid, IH.customerid,                                           
 IH.invoicedate, iH.invoiceno, isnull(ih.referenceno,''), ih.remarks, serinvhamount,                                           
 ' > 90' as Due  , 'SBI' as type,'Trade Debtors' Debtortype, ih.serinvhupdatetime,                                           
 customercategory, IH.serinvhduedate duedate,ih.seinvhdepexrate as depExRate,                                          
 1802 InterfaceID, serinvhpreparedby SalesPersonID, c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
 serinvhTaxamount TaxAmount  --Ref.No.5                                        
FROM ashops s, acustomermaster c, vwbookingservinvoices IH                                           
where s.shopid = ih.shopid and s.accountable is not null and c.customerid = ih.customerid and                                          
 datediff(dd,IH.InvoiceDate,getdate()) > 90                                          
                                          
union all                                          
-- for shop debit credit note                                          
SELECT losdcnCompanyID, losdcnshopid, losdcndepartmentid, losdcnid, losdcncustomerid,                                           
 losdcndate, losdcnno, isnull(losreferenceno,''), losdcnremarks, losdcnamount,                                           
 '0 - 30' as Due  , 'sdcn' as type,'Trade Debtors' Debtortype, updatetime,                                           
 customercategory, losdcndate, losdepexrate as depExRate,1517 InterfaceID,                                          
 0 SalesPersonID, c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
 0.0 TaxAmount  --Ref.No.5                                        
FROM  ashops s, acustomermaster c, losdebitcreditnote                                           
where s.shopid = losdcnshopid and s.accountable is not null and                                           
 c.customerid = losdcncustomerid and losdcncancelled =0 and losdcndebit =1 and                                           
 losdcncustomerid is not null and datediff(dd,losdcnDate,getdate()) between 0 and 30                                          
                                          
union all                                          
-- for shop debit credit note                                          
SELECT losdcnCompanyID, losdcnshopid, losdcndepartmentid, losdcnid, losdcncustomerid,                                           
 losdcndate, losdcnno, isnull(losreferenceno,''), losdcnremarks, losdcnamount,                                           
 '31 - 60' as Due , 'sdcn' as type,'Trade Debtors' Debtortype, updatetime,                                           
 customercategory, losdcndate, losdepexrate as depExRate,1517 InterfaceID,                            
 0 SalesPersonID, c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
 0.0 TaxAmount --Ref.No.5                                         
FROM  ashops s, acustomermaster c, losdebitcreditnote                                           
where s.shopid = losdcnshopid and s.accountable is not null and c.customerid = losdcncustomerid             
 and losdcncustomerid is not null and losdcncancelled =0 and losdcndebit =1 and      
datediff(dd,losdcnDate,getdate()) between 31 and 60                                          
                                          
union all                                          
-- for shop debit credit note                       
SELECT losdcnCompanyID, losdcnshopid, losdcndepartmentid, losdcnid, losdcncustomerid,                                           
 losdcndate, losdcnno, isnull(losreferenceno,''), losdcnremarks, losdcnamount,                                           
 '61 - 90' as Due  , 'sdcn' as type,'Trade Debtors' Debtortype, updatetime,                                           
 customercategory, losdcndate, losdepexrate as depExRate,1517 InterfaceID,                                          
 0 SalesPersonID, c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
 0.0 TaxAmount --Ref.No.5                                         
FROM ashops s, acustomermaster c, losdebitcreditnote                                           
where s.shopid = losdcnshopid and s.accountable is not null and c.customerid = losdcncustomerid and             
  losdcncustomerid is not null and losdcncancelled =0 and losdcndebit =1 and                                            
  datediff(dd,losdcnDate,getdate()) between 61 and 90                                          
                                          
union all                                          
-- for shop debit credit note                                          
SELECT losdcnCompanyID, losdcnshopid, losdcndepartmentid, losdcnid, losdcncustomerid,                                           
  losdcndate, losdcnno, isnull(losreferenceno,''), losdcnremarks, losdcnamount,                                           
  ' > 90' as Due  , 'sdcn' as type,'Trade Debtors' Debtortype, updatetime,                                           
  customercategory, losdcndate, losdepexrate as depExRate,1517 InterfaceID,                                          
  0 SalesPersonID,c.CustomerType, 0.0 DutyAmt,0.0 CostPrice  ,CustGroupName,    
  0.0 TaxAmount --Ref.No.5                                         
FROM ashops s, acustomermaster c, losdebitcreditnote                                           
where s.shopid = losdcnshopid and s.accountable is not null and c.customerid = losdcncustomerid and             
  losdcncustomerid is not null and losdcncancelled =0 and losdcndebit =1                                           
  and  datediff(dd,losdcnDate,getdate()) > 90                                          
                             
union all                                          
                                          
SELECT IH.reHCompanyID, ih.reHshopid, IH.reHDepartmentID, IH.reHExportID, IH.rehcustomerid,                                           
 IH.rehExportdate, iH.rehExportNo, isnull(ih.rehReferenceNo,'') Referenceno,                                           
 ih.rehremarks,isnull(sum(rehExportAmount),0) as InvAmt, '0 - 30' as Due  ,                                           
 'RE' as type,'Trade Debtors' Debtortype, ih.rehupdatetime, customercategory,                                           
 rehDueDate duedate,avg(ih.rehDepExRate) as depExRate,1529 InterfaceID,                                          
 ih.rehSalesPersonID SalesPersonID, c.CustomerType, 0.0 DutyAmt,                                          
 sum(isnull(redQuantity * redCostPrice,0)) CostPrice  ,CustGroupName,    
 0.0 TaxAmount --Ref.No.5                                         
FROM  ashops s, acustomermaster c,   losExportHeader IH                                          
 Left outer join losExportDetail SID on IH.rehExportID = SID.redExportID and ih.reHshopid=sid.redshopid                                          
WHERE  s.shopid = ih.rehshopid and s.accountable is not null and                                           
 ih.rehcustomerid = c.customerid and IH.rehCashInvoice = 0 and IH.rehProforma = 0 and                                           
 IH.rehCancelled = 0 and IH.rehtype = 'i' and rehcustomerid is not null and                                           
 (datediff(dd,IH.rehExportDate,getdate()) between 0 and 30)                     
GROUP BY  IH.rehCompanyID, IH.rehSHOPID, IH.rehExportID , sID.redExportID, IH.rehcustomerid,                                           
 IH.rehDepartmentID, IH.rehExportDate, ih.rehupdatetime, iH.rehExportNo,                                           
 ih.rehReferenceNo, ih.rehremarks, IH.rehDiscount, customercategory, rehDueDate ,                                          
 ih.rehSalesPersonID,c.CustomerType ,CustGroupName                                         
                                          
union all                          
                                          
SELECT IH.reHCompanyID, ih.reHshopid, IH.reHDepartmentID, IH.reHExportID, IH.rehcustomerid,                                           
 IH.rehExportdate, iH.rehExportNo, isnull(ih.rehReferenceNo,'') Referenceno,                                           
 ih.rehremarks,isnull(sum(redunitprice),0) as InvAmt, '31 - 60' as Due  ,                                           
 'RE' as type,'Trade Debtors' Debtortype, ih.rehupdatetime, customercategory,                  
 rehDueDate duedate,avg(ih.rehDepExRate) as depExRate,1529 InterfaceID,                                          
 ih.rehSalesPersonID SalesPersonID, c.CustomerType, 0.0 DutyAmt,                                          
 sum(isnull(redQuantity * redCostPrice,0)) CostPrice  ,CustGroupName,    
 0.0 TaxAmount --Ref.No.5                                         
FROM ashops s, acustomermaster c, losExportHeader IH                                          
 Left outer join losExportDetail SID  on IH.rehExportID = SID.redExportID and ih.reHshopid=sid.redshopid                                          
WHERE s.shopid = ih.rehshopid and s.accountable is not null and                                           
 ih.rehcustomerid = c.customerid and IH.rehCashInvoice = 0 and IH.rehProforma = 0 and                                           
 IH.rehCancelled = 0 and IH.rehtype = 'i' and (datediff(dd,IH.rehExportDate,getdate()) between 31 and 60)                                            
 and rehcustomerid is not null                                
GROUP BY IH.rehCompanyID, IH.rehSHOPID, IH.rehExportID , sID.redExportID, IH.rehcustomerid,                                           
 IH.rehDepartmentID, IH.rehExportDate, ih.rehupdatetime, iH.rehExportNo,                                           
 ih.rehReferenceNo, ih.rehremarks, IH.rehDiscount, customercategory, rehDueDate ,                                          
 ih.rehSalesPersonID, c.CustomerType ,CustGroupName                                          
                                          
union all                                          
                                          
SELECT IH.reHCompanyID, ih.reHshopid, IH.reHDepartmentID, IH.reHExportID, IH.rehcustomerid,                                         
 IH.rehExportdate, iH.rehExportNo, isnull(ih.rehReferenceNo,'') Referenceno,                                           
 ih.rehremarks,isnull(sum(redunitprice),0) as InvAmt,                                  
 '61 - 90' as Due  , 'RE' as type,'Trade Debtors' Debtortype, ih.rehupdatetime,                                           
 customercategory, rehDueDate duedate,avg(ih.rehDepExRate) as depExRate,1529 InterfaceID,                                          
 ih.rehSalesPersonID SalesPersonID, c.CustomerType, 0.0 DutyAmt,                                          
 sum(isnull(redQuantity * redCostPrice,0)) CostPrice  ,CustGroupName,    
 0.0 TaxAmount --Ref.No.5                                         
FROM ashops s, acustomermaster c, losExportHeader IH                                          
 Left outer join losExportDetail SID                                           
 on IH.rehExportID = SID.redExportID and ih.reHshopid=sid.redshopid                                          
WHERE  s.shopid = ih.rehshopid and s.accountable is not null and                                           
 ih.rehcustomerid = c.customerid and IH.rehCashInvoice = 0 and IH.rehProforma = 0 and                                           
 IH.rehCancelled = 0 and IH.rehtype = 'i' and rehcustomerid is not null                                          
 and (datediff(dd,IH.rehExportDate,getdate()) between 61 and 90)                          
GROUP BY IH.rehCompanyID, IH.rehSHOPID, IH.rehExportID , sID.redExportID, IH.rehcustomerid,                          
 IH.rehDepartmentID, IH.rehExportDate, ih.rehupdatetime, iH.rehExportNo,                                           
 ih.rehReferenceNo, ih.rehremarks, IH.rehDiscount, customercategory, rehDueDate,                                          
 ih.rehSalesPersonID, c.CustomerType ,CustGroupName                  
                                     
union all                                          
                                          
SELECT  IH.reHCompanyID, ih.reHshopid, IH.reHDepartmentID, IH.reHExportID, IH.rehcustomerid,                                           
 IH.rehExportdate, iH.rehExportNo, isnull(ih.rehReferenceNo,'') Referenceno, ih.rehremarks,                            
 isnull(sum(redunitprice),0) as InvAmt,'> 90' as Due  , 'RE' as type,'Trade Debtors' Debtortype,             
 ih.rehupdatetime,customercategory,rehDueDate duedate,avg(ih.rehDepExRate) as depExRate,1529 InterfaceID,                                          
 ih.rehSalesPersonID SalesPersonID, c.CustomerType, 0 DutyAmt,                                          
 sum(isnull(redQuantity * redCostPrice,0)) CostPrice,CustGroupName,    
 0.0 TaxAmount --Ref.No.5                                         
FROM ashops s, acustomermaster c, losExportHeader IH                                          
 Left outer join losExportDetail SID on IH.rehExportID = SID.redExportID and ih.reHshopid=sid.redshopid                                          
WHERE s.shopid = ih.rehshopid and s.accountable is not null and                                           
 ih.rehcustomerid = c.customerid and IH.rehCashInvoice = 0 and IH.rehProforma = 0 and                             
 IH.rehCancelled = 0 and IH.rehtype = 'i' and rehcustomerid is not null and                                           
 (datediff(dd,IH.rehExportDate,getdate()) > 90)                                            
GROUP BY IH.rehCompanyID, IH.rehSHOPID, IH.rehExportID , sID.redExportID, IH.rehcustomerid,                                           
 IH.rehDepartmentID, IH.rehExportDate, ih.rehupdatetime, iH.rehExportNo,                                           
 ih.rehReferenceNo, ih.rehremarks, IH.rehDiscount, customercategory, rehDueDate ,                                          
 ih.rehSalesPersonID, c.CustomerType ,CustGroupName                                         
                                          
UNION ALL                                          
--Room Billing Manaam                                           
SELECT abh.abhCompanyid, abhSHopID shopid, abh.abhDepartmentid, abh.abhBillId,                               
 abh.abhCustomerid, abh.abhBillDate, abh.abhBillNo, isnull(abh.abhReferenceno,'')                                           
 Referenceno, abh.abhRemarks, (abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn)                                          
 as InvAmt ,'0 - 30' as Due, 'RBI' AS Type ,'Trade Debtors' Debtortype,                                          
 abh.abhUpdateTime, CustomerCategory, abh.abhDueDate duedate,                                         
 abh.abhDepExRate as depexrate,2304 InterFaceID,                                           
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice ,CustGroupName,    
 0.0 TaxAmount --Ref.No.5                 
FROM  losApartmentBillHeader abh, acustomermaster c                                          
WHERE  abh.abhCustomerID=c.customerID and abh.abhCashAccId is null and                                          
 abh.abhCancelled=0 and (datediff(dd,abh.abhBillDate,getdate()) between 0 and 30) and                                          
 isnull(abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn,0) >0.0                                          
                                          
UNION ALL                                          
                                          
SELECT abh.abhCompanyid, abhSHopID shopid, abh.abhDepartmentid, abh.abhBillId,                                          
 abh.abhCustomerid, abh.abhBillDate, abh.abhBillNo, isnull(abh.abhReferenceno,'')                                           
 Referenceno, abh.abhRemarks, (abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn)                                          
 as InvAmt ,'31 - 60' as Due, 'RBI' AS Type ,'Trade Debtors' Debtortype,                                          
 abh.abhUpdateTime, CustomerCategory, abh.abhDueDate duedate,                                           
 abh.abhDepExRate as depexrate,2304 InterFaceID,                                           
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
 0.0 TaxAmount --Ref.No.5                            
FROM  losApartmentBillHeader abh, acustomermaster c                                   
WHERE abh.abhCustomerID=c.customerID and abh.abhCashAccId is null and                
 abh.abhCancelled=0 and (datediff(dd,abh.abhBillDate,getdate()) between 31 and 60) and                                          
 isnull(abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn,0) >0.0                                          
                                          
UNION ALL                                          
                                          
SELECT abh.abhCompanyid, abhSHopID shopid, abh.abhDepartmentid, abh.abhBillId,                                          
 abh.abhCustomerid, abh.abhBillDate, abh.abhBillNo, isnull(abh.abhReferenceno,'')                                           
 Referenceno, abh.abhRemarks, (abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn)                                          
 as InvAmt ,'61 - 90' as Due, 'RBI' AS Type ,'Trade Debtors' Debtortype,                                          
 abh.abhUpdateTime, CustomerCategory, abh.abhDueDate duedate,                                           
 abh.abhDepExRate as depexrate,2304 InterFaceID,                                           
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice ,CustGroupName,    
 0.0 TaxAmount --Ref.No.5                                          
FROM  losApartmentBillHeader abh, acustomermaster c                                          
WHERE abh.abhCustomerID=c.customerID and abh.abhCashAccId is null and                                          
 abh.abhCancelled=0 and (datediff(dd,abh.abhBillDate,getdate()) between 61 and 90) and                                          
 isnull(abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn,0) >0.0                                          
                                      
UNION ALL                                          
                                          
SELECT abh.abhCompanyid, abhSHopID shopid, abh.abhDepartmentid, abh.abhBillId,                                          
 abh.abhCustomerid, abh.abhBillDate, abh.abhBillNo, isnull(abh.abhReferenceno,'')                                           
 Referenceno, abh.abhRemarks, (abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn)                                          
 as InvAmt ,'> 90' as Due, 'RBI' AS Type ,'Trade Debtors' Debtortype,                                          
 abh.abhUpdateTime, CustomerCategory, abh.abhDueDate duedate,                                           
 abh.abhDepExRate as depexrate,2304 InterFaceID,                                           
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
 0.0 TaxAmount --Ref.No.5                                           
FROM losApartmentBillHeader abh, acustomermaster c                       
WHERE abh.abhCustomerID=c.customerID and abh.abhCashAccId is null and                                          
abh.abhCancelled=0 and (datediff(dd,abh.abhBillDate,getdate())) > 90 and                                          
 isnull(abh.abhAmount+abh.abhOtherCharges-abh.abdDepositReturn,0) >0.0                                          
                                          
UNION ALL                                          
--Utility Billing for Manaam                                          
SELECT tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhDepartmentid, tbh.tbhBillId,                                          
 tbh.tbhCustomerid, tbh.tbhBillDate, tbh.tbhBillNo, isnull(tbh.tbhReferenceno,'')                                           
 Referenceno, tbh.tbhRemarks, isnull(tbh.tbhAmount,0)                                          
 as InvAmt ,'0 - 30' as Due, 'UTB' AS Type ,'Trade Debtors' Debtortype,                                          
 tbh.tbhUpdateTime, CustomerCategory, tbh.tbhDueDate duedate,tbh.tbhDepExRate as depexrate,            
 2305 InterFaceID,0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice ,CustGroupName,    
 0.0 TaxAmount  --Ref.No.5                                         
FROM losTenantServiceBillHeader tbh, acustomermaster c                                          
WHERE tbh.tbhCustomerID=c.customerID and tbh.tbhBankCashID is null and                                          
 tbh.tbhCancelled=0 and (datediff(dd,tbh.tbhBillDate,getdate()) between 0 and 30) and                                          
 isnull(tbh.tbhAmount,0) >0.0                                          
                                          
UNION ALL                                          
                                          
SELECT tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhDepartmentid, tbh.tbhBillId,                                          
 tbh.tbhCustomerid, tbh.tbhBillDate, tbh.tbhBillNo, isnull(tbh.tbhReferenceno,'')                                           
 Referenceno, tbh.tbhRemarks, isnull(tbh.tbhAmount,0)as InvAmt ,'31 - 60' as Due, 'UTB' AS Type ,            
 'Trade Debtors' Debtortype,tbh.tbhUpdateTime, CustomerCategory, tbh.tbhDueDate duedate,                                           
 tbh.tbhDepExRate as depexrate,2305 InterFaceID,0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
 0.0 TaxAmount  --Ref.No.5                                          
FROM losTenantServiceBillHeader tbh, acustomermaster c                                          
WHERE tbh.tbhCustomerID=c.customerID and tbh.tbhBankCashID is null and tbh.tbhCancelled=0 and             
  (datediff(dd,tbh.tbhBillDate,getdate()) between 31 and 60) and  isnull(tbh.tbhAmount,0) >0.0                                          
                                   
UNION ALL                                          
                                          
SELECT tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhDepartmentid, tbh.tbhBillId,                                          
 tbh.tbhCustomerid, tbh.tbhBillDate, tbh.tbhBillNo, isnull(tbh.tbhReferenceno,'')                                           
 Referenceno, tbh.tbhRemarks, isnull(tbh.tbhAmount,0)as InvAmt ,'61 - 90' as Due, 'UTB' AS Type ,            
 'Trade Debtors' Debtortype,tbh.tbhUpdateTime, CustomerCategory, tbh.tbhDueDate duedate,                                           
 tbh.tbhDepExRate as depexrate,2305 InterFaceID,                                           
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
 0.0 TaxAmount  --Ref.No.5                                         
FROM losTenantServiceBillHeader tbh, acustomermaster c                                          
WHERE tbh.tbhCustomerID=c.customerID and tbh.tbhBankCashID is null and                                          
 tbh.tbhCancelled=0 and (datediff(dd,tbh.tbhBillDate,getdate()) between 61 and 90) and                                          
 isnull(tbh.tbhAmount,0)>0.0                                          
                                          
UNION ALL                                          
                                          
SELECT tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhDepartmentid, tbh.tbhBillId,                                          
 tbh.tbhCustomerid, tbh.tbhBillDate, tbh.tbhBillNo, isnull(tbh.tbhReferenceno,'')           
 Referenceno, tbh.tbhRemarks, isnull(tbh.tbhAmount,0) as InvAmt ,'> 90' as Due, 'UTB' AS Type ,            
 'Trade Debtors' Debtortype,tbh.tbhUpdateTime, CustomerCategory, tbh.tbhDueDate duedate,                                           
 tbh.tbhDepExRate as depexrate,2305 InterFaceID,                                           
 0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
 0.0 TaxAmount --Ref.No.5                                         
FROM losTenantServiceBillHeader tbh, acustomermaster c                                          
WHERE tbh.tbhCustomerID=c.customerID and tbh.tbhBankCashID is null and tbh.tbhCancelled=0 and             
 (datediff(dd,tbh.tbhBillDate,getdate())) > 90 and isnull(tbh.tbhAmount,0) >0.0                                     
            
UNION ALL                                    
 --Fine Invoice                               
select fhCompanyID,0,fhDepartmentID,fhFineID,fhCustomerID,fhLastFineCalDate,fhFineNo,                                    
  fhInvoiceNo Referenceno,'' Remarks,FineAmount as InvAmt,'0-30' as Due,                     
  'FINE' as Type,'Trade Debtors' Debtortype,fhLastFineCalDate UpdatedTime,CustomerCategory,                                    
  fhLastFineCalDate duedate,fhDepExchangeRate as depexrate,0 InterFaceID,                                    
  0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
  0.0 TaxAmount --Ref.No.5                              
from aFineHEader             
  inner join  (select fdFineID,sum(fdFineAmount*fhRespExchangeRate) FineAmount from                           
 afineheader inner join aFineDetail on fhFineID=fdFineID Group by fdFineID) fd                                     
 on fhFineID=fd.fdFineID and  isnull(fhInvoiceCancelled,0)=0  inner join acustomermaster c                                    
 on fhCustomerID=CustomerID                               
                                    
UNION ALL                                    
                                    
select fhCompanyID,0,fhDepartmentID,fhFineID,fhCustomerID,fhLastFineCalDate,fhFineNo,                                    
  fhInvoiceNo Referenceno,'' Remarks,FineAmount as InvAmt,'31-60' as Due,                                    
  'FINE' as Type,'Trade Debtors' Debtortype,fhLastFineCalDate UpdatedTime,CustomerCategory,                                    
  fhLastFineCalDate duedate,fhDepExchangeRate as depexrate,0 InterFaceID,                                    
  0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
  0.0 TaxAmount --Ref.No.5                                    
from aFineHEader inner join                                     
  (select fdFineID,sum(fdFineAmount*fhRespExchangeRate) FineAmount from            
 afineheader inner join aFineDetail on fhFineID=fdFineID                          
  Group by fdFineID) fd                                      
  on fhFineID=fd.fdFineID and  isnull(fhInvoiceCancelled,0)=0  inner join acustomermaster c                                    
  on fhCustomerID=CustomerID and  (datediff(dd,fhLastFineCalDate,getdate())  between 31 and 60)                                
                                    
Union ALL                                    
select fhCompanyID,0,fhDepartmentID,fhFineID,fhCustomerID,fhLastFineCalDate,fhFineNo,                                    
  fhInvoiceNo Referenceno,'' Remarks,FineAmount as InvAmt,'61-90' as Due,                                    
  'FINE' as Type,'Trade Debtors' Debtortype,fhLastFineCalDate UpdatedTime,CustomerCategory,               
  fhLastFineCalDate duedate,fhDepExchangeRate as depexrate,0 InterFaceID,                                    
  0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
  0.0 TaxAmount --Ref.No.5                                    
from aFineHEader inner join                                     
  (select fdFineID,sum(fdFineAmount*fhRespExchangeRate) FineAmount from                           
  afineheader inner join aFineDetail on fhFineID=fdFineID                          
Group by fdFineID) fd                                      
  on fhFineID=fd.fdFineID and  isnull(fhInvoiceCancelled,0)=0  inner join acustomermaster c                        
  on fhCustomerID=CustomerID and  (datediff(dd,fhLastFineCalDate,getdate())  between 61 and 90)                               
                                    
UNION ALL                     
                                    
select fhCompanyID,0,fhDepartmentID,fhFineID,fhCustomerID,fhLastFineCalDate,fhFineNo,                                    
  fhInvoiceNo Referenceno,'' Remarks,FineAmount as InvAmt,'>90' as Due,                                    
  'FINE' as Type,'Trade Debtors' Debtortype,fhLastFineCalDate UpdatedTime,CustomerCategory,                                    
  fhLastFineCalDate duedate,fhDepExchangeRate as depexrate,0 InterFaceID,                              
  0 SalesPersonID, c.CustomerType,0.0 DutyAmt,0.0 CostPrice,CustGroupName,    
  0.0 TaxAmount --Ref.No.5                          
from aFineHEader inner join                                     
  (select fdFineID,sum(fdFineAmount*fhRespExchangeRate) FineAmount from                           
  afineheader inner join aFineDetail on fhFineID=fdFineID Group by fdFineID) fd                                  
  on fhFineID=fd.fdFineID and  isnull(fhInvoiceCancelled,0)=0  inner join acustomermaster c                                    
  on fhCustomerID=CustomerID and  (datediff(dd,fhLastFineCalDate,getdate()) >90)                     
            
---FandB Invoce                     
UNION ALL                         
select vw.CompanyID ,poshShopID ,departmentid ,poshBillID ,poshcustomerid,poshBillDate,poshBillNo, '',            
  '' ,poshBillAmount,'0-30','fandb','fandb',poshBillDate uptime  ,vw.customercategory ,duedate                     
  ,1,92010,0,c.CustomerType,0 DutyAmt,0.0 CostPrice  ,vw.CustGroupName,    
  fb_pd_DishTaxAmount TaxAmount --Ref.No.5                
from vwFANDBInvoice  vw ,acustomermaster c             
where vw.poshcustomerid=c.CustomerID and  (datediff(dd,poshBillDate,getdate())  between 0 and 30)                    
            
UNION ALL                     
select vw.CompanyID ,poshShopID ,departmentid ,poshBillID ,poshcustomerid,poshBillDate,poshBillNo, '',                    
  '' ,poshBillAmount,'31 - 60','fandb','fandb',poshBillDate uptime  ,vw.customercategory ,duedate                     
  ,1,92010,0,c.CustomerType,0 DutyAmt,0.0 CostPrice  ,vw.CustGroupName,    
  fb_pd_DishTaxAmount TaxAmount --Ref.No.5                
from vwFANDBInvoice  vw ,acustomermaster c             
where vw.poshcustomerid=c.CustomerID and  (datediff(dd,poshBillDate,getdate())  between 31 and 60)                    
             
UNION all                    
select vw.CompanyID ,poshShopID ,departmentid ,poshBillID ,poshcustomerid,poshBillDate,poshBillNo, '',                    
  '' ,poshBillAmount,'61 - 90','fandb','fandb',poshBillDate uptime  ,vw.customercategory ,duedate                     
  ,1,92010,0,c.CustomerType,0 DutyAmt,0.0 CostPrice  ,vw.CustGroupName,    
  fb_pd_DishTaxAmount TaxAmount --Ref.No.5                
from vwFANDBInvoice  vw ,acustomermaster c             
where vw.poshcustomerid=c.CustomerID and  (datediff(dd,poshBillDate,getdate())  between 61 and 90)                    
            
UNION all                    
select vw.CompanyID ,poshShopID ,departmentid ,poshBillID ,poshcustomerid,poshBillDate,poshBillNo, '',                    
  '' ,poshBillAmount,' > 90','fandb','fandb',poshBillDate uptime  ,vw.customercategory ,duedate                     
  ,1,92010,0,c.CustomerType,0 DutyAmt,0.0 CostPrice  ,vw.CustGroupName,    
  fb_pd_DishTaxAmount TaxAmount --Ref.No.5                
from vwFANDBInvoice  vw ,acustomermaster c             
where vw.poshcustomerid=c.CustomerID   and (datediff(dd,poshBillDate,getdate())>90) 

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:QPY-495288
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE ADMINV2
GO
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = N'dbo' AND TABLE_NAME = N'vwhpCustomerLedgerforReport' )   
DROP VIEW vwhpCustomerLedgerforReport
GO     
/*          
Created by : AADYAKUMAR.D.V          
Created on : 17/09/2012         
Purpose : To make uniform data collecting in HP debtor ageing and customer balance
Comment  : This view is created by comparing vwhpCustomerLedger with vwHpInvoice and vwHpSettlement
*/ --------------------------------         
create view vwhpCustomerLedgerforReport as          
---Shop HP Invoice          
select inh.hpqhCompanyID as CompanyID,s.DepartmentID,inh.hpqhCustomerID as CustomerID,inh.hpqhQuotationDate as tDate,refno as secref,          
inh.hpqhQuotationNO tno,'' as cr,'HP Invoice' as type,inh.hpqhRemarks,inh.hpqhInstPrice invamt,0.0 pmtamt          
,datediff(dd,inh.hpqhQuotationDate,getdate()) age,inh.hpqhUpdatetime,inh.hpqhInstPrice cinvamt,          
0.0 cpmtamt,inh.hpqhFinancialID,inh.hpqhInstPrice dinvamt,0.0 dpmtamt,          
c.customercategory,isnull(c.custgroupname,'')custgroupname,null duedate,'' chequedetails          
from          
loshpInvoiceheader inh inner join ashops s on inh.hpqhShopId=s.ShopID          
inner join aCustomerMaster c on inh.hpqhCustomerID=c.CustomerID          
left outer Join vwShopHPInvoiceSettlementNo vw on inh.hpqhCustomerID = vw.customerid And          
inh.hpqhShopId=vw.ShopID and inh.hpqhQuotationID=vw.accinvoiceid          
where inh.hpqhCancel=0 and inh.hpqhType='I' 
and hpqhConfirmed=1 --aadya        
          
-------HQ HP Payment          
union all          
select inr.hphCompanyId as CompanyID,inr.hphDepartmentID,inr.hphCustomerID as CustomerID,inr.hphPaymentdate as tDate,'' as secref,          
inr.hphPaymentNo tno,'' as cr,'HP Payment' as type,inr.hphRemarks,          
convert(numeric(18,2),((inr.hphPaymentAmount/inr.hphBankExchangeRate)* inr.hphCusExchangeRate)) invamt,0.0 pmtamt,          
datediff(dd,inr.hphPaymentdate,getdate()) age,inr.hphupdateTime,          
convert(numeric(18,2),((inr.hphPaymentAmount/inr.hphBankExchangeRate)* inr.hphComExchangeRate)) cinvamt, 0.0 cpmtamt,inr.hphFinancialID,          
convert(numeric(18,2),((inr.hphPaymentAmount/inr.hphBankExchangeRate)* inr.hphDepExchangeRate)) dinvamt,0.0 dpmtamt,          
c.customercategory,isnull(c.custgroupname,'')custgroupname,null duedate,'' chequedetails          
from aHppaymentHeader inr inner join aCustomerMaster c on inr.hphCustomerID=c.CustomerID          
where hphCancel=0          
-------Shop HP Receipt (Hp Settlements)         
union all 
--aadya         
----select reh.hprhCompanyID as CompanyID,s.DepartmentID,reh.hprhCustomerID as CustomerID,reh.hprhReceiptDate as tDate,'' as secref,          
----reh.hprhReceiptNo tno,'' as cr,'Shop Receipt' as type,reh.hprhRemarks,0.0 invamt,reh.hprhReceiptAmount pmyamt,          
----datediff(dd,reh.hprhReceiptDate,getdate())age,reh.hprhUpdatetime,          
----0.0 cinvamt, reh.hprhReceiptAmount cpmtamt,reh.hprhFinancialID, 0.0 Dinvamt, reh.hprhReceiptAmount dpmtamt,          
----c.customercategory,isnull(c.custgroupname,'')custgroupname,null duedate,reh.hprhChequeNo as chequedetails  
------aadya        
------from loshpreceiptheader reh inner join ashops s on reh.hprhShopId=s.ShopID          
------inner join aCustomerMaster c on reh.hprhCustomerId=c.CustomerID          
------where reh.hprhCancel=0 
----from loshpreceiptheader reh 
----INNER JOIN loshpreceiptDetail red
----on reh.hprhReceiptID=red.hprdReceiptID and reh.hprhShopID=red.hprdShopID
----and reh.hprhCancel=0 and hprhReceiptType='S'
----inner join ashops s 
----on reh.hprhShopId=s.ShopID          
----inner join aCustomerMaster c 
----on reh.hprhCustomerId=c.CustomerID
select reh.hprhCompanyID as CompanyID,s.DepartmentID,reh.hprhCustomerID as CustomerID,reh.hprhReceiptDate as tDate,'' as secref,          
reh.hprhReceiptNo tno,'' as cr,'Shop Receipt' as type,reh.hprhRemarks,0.0 invamt,
--sum(reh.hprhReceiptAmount) pmyamt,  
sum(hprdSettelmentAmount) SettledAmt,        
datediff(dd,reh.hprhReceiptDate,getdate())age,reh.hprhUpdatetime,          
0.0 cinvamt,
--SUM(reh.hprhReceiptAmount) cpmtamt,
sum(hprdSettelmentAmount) cSettledAmt,
reh.hprhFinancialID, 0.0 Dinvamt,
--SUM(reh.hprhReceiptAmount) dpmtamt,
sum(hprdSettelmentAmount) dSettledAmt,          
c.customercategory,isnull(c.custgroupname,'')custgroupname,null duedate,reh.hprhChequeNo as chequedetails  
--aadya        
--from loshpreceiptheader reh inner join ashops s on reh.hprhShopId=s.ShopID          
--inner join aCustomerMaster c on reh.hprhCustomerId=c.CustomerID          
--where reh.hprhCancel=0 
from loshpreceiptheader reh 
INNER JOIN loshpreceiptDetail red
on reh.hprhReceiptID=red.hprdReceiptID and reh.hprhShopID=red.hprdShopID
and reh.hprhCancel=0 and hprhReceiptType='S'
inner join ashops s 
on reh.hprhShopId=s.ShopID          
inner join aCustomerMaster c 
on reh.hprhCustomerId=c.CustomerID  
group By reh.hprhCustomerID ,reh.hprhReceiptNo  ,reh.hprhCompanyID  ,red.hprdInvoiceID ,                         
reh.hprhShopId , reh.hprhReceiptDate , s.DepartmentID,reh.hprhRemarks,reh.hprhUpdatetime,reh.hprhFinancialID,c.customercategory  
,c.custgroupname,reh.hprhChequeNo 
--aadya 
 
-------Shop HP Receipt (HP Advance Receipts)         
union all          
select reh.hprhCompanyID as CompanyID,s.DepartmentID,reh.hprhCustomerID as CustomerID,reh.hprhReceiptDate as tDate,'' as secref,          
reh.hprhReceiptNo tno,'' as cr,'Shop Receipt' as type,reh.hprhRemarks,0.0 invamt,reh.hprhReceiptAmount pmyamt,          
datediff(dd,reh.hprhReceiptDate,getdate())age,reh.hprhUpdatetime,          
0.0 cinvamt, reh.hprhReceiptAmount cpmtamt,reh.hprhFinancialID, 0.0 Dinvamt, reh.hprhReceiptAmount dpmtamt,          
c.customercategory,isnull(c.custgroupname,'')custgroupname,null duedate,reh.hprhChequeNo as chequedetails          
 from loshpreceiptheader reh 
  inner join aCustomerMaster c 
on reh.hprhCustomerId=c.CustomerID
 Inner Join (select hpqhShopID,hpqhQuotationID,hpqhReferenceID 
 from loshpInvoiceheader                     
 where hpqhCancel=0 and hpqhType='I')Inv on inv.hpqhShopID= reh.hprhShopId 
 and inv.hpqhReferenceID=hprhHPQuotationID ,  ashops s                      
where reh.hprhCancel=0   and reh.hprhShopId=s.ShopID and hprhReceiptType='A'         
         
-------HQ HP Receipts          
union all          
----select rph.hprhCompanyId as CompanyID,rph.hprhDepartmentID,rph.hprhCustomerID as CustomerID,rph.hprhReceiptDate as tDate,'' as secref,          
----rph.hprhReceiptNo tno,'' as cr,'HP Receipt' as type,rph.hprhRemarks,0.0 invamt,          
----convert(numeric(18,2),((rph.hprhamount/rph.hprhBankExRate)*rph.hprhCusExRate))-isnull(hprhCreditAmount,0) pmtamt,          
----datediff(dd,rph.hprhReceiptDate,getdate())age,rph.hprhUpdatedTime,          
----0.0 cinvamt,convert(numeric(18,2),((rph.hprhamount/rph.hprhBankExRate)*rph.hprhComExRate)) cpmtamt,          
----rph.hprhFinancialID,0.0 Dinvamt,          
----convert(numeric(18,2),((rph.hprhamount/rph.hprhBankExRate)*rph.hprhDepExRate)) dpmtamt,          
----c.customercategory,isnull(c.custgroupname,'')custgroupname,null duedate,rph.hprhChequeNo as chequedetails          
----from ahpReceiptHeader rph inner join aCustomermaster c on rph.hprhCustomerid=c.CustomerID          
----where hprhCancel=0 

	select rph.hprhCompanyId as CompanyID,rph.hprhDepartmentID,rph.hprhCustomerID as CustomerID,rph.hprhReceiptDate as tDate,'' as secref,          
	rph.hprhReceiptNo tno,'' as cr,'HP Receipt' as type,rph.hprhRemarks,0.0 invamt,
	--check below again          
	--convert(numeric(18,2),((rph.hprhamount/rph.hprhBankExRate)*rph.hprhCusExRate))-isnull(hprhCreditAmount,0) pmtamt, 
	convert(numeric(18,2),((rpd.hprdSettledAmnt/rph.hprhBankExRate)*rph.hprhCusExRate))-isnull(hprhCreditAmount,0) pmtamt,         
	datediff(dd,rph.hprhReceiptDate,getdate())age,rph.hprhUpdatedTime,          
	0.0 cinvamt
	--,convert(numeric(18,2),((rph.hprhamount/rph.hprhBankExRate)*rph.hprhComExRate)) cpmtamtold 
	,convert(numeric(18,2),((rpd.hprdSettledAmnt/rph.hprhBankExRate)*rph.hprhComExRate))cpmtamt,         
	rph.hprhFinancialID,0.0 Dinvamt,          
	--convert(numeric(18,2),((rph.hprhamount/rph.hprhBankExRate)*rph.hprhDepExRate)) dpmtamt, 
	convert(numeric(18,2),((rpd.hprdSettledAmnt/rph.hprhBankExRate)*rph.hprhDepExRate))dpmtamt,         
	c.customercategory,isnull(c.custgroupname,'')custgroupname,null duedate,rph.hprhChequeNo as chequedetails          
	from ahpReceiptHeader rph 
	inner join ahpReceiptDetail rpd  on hprhCompanyID=hprdCompanyID 
	And hprhDepartmentID=hprdDepartmentID And hprhReceiptID =hprdReceiptID
	inner join aCustomermaster c 
	on rph.hprhCustomerid=c.CustomerID          
	where hprhCancel=0 and rpd.hprdSettledAmnt <>0
--aadya     
union all    
    
--HP Reprocessing After Settlement          
select phR.hphCompanyID as CompanyID,phR.hphDepartmentID as DepartmentID,phR.hphCustomerID as CustomerID,phR.hphProcessingDate as tDate,''as secref,    
phR.hphProcessingNo as tno ,'' as cr,'HP Adjustment' as type,phr.hphRemarks, 0.00 invamt,(phR.hphAdjustmentAmount) as pmtamt,    
'' as age,phR.hphUpdateTime,0.0 cinvamt,(phR.hphAdjustmentAmount) as cpmtamt,phR.hphFinancialID,0.00 Dinvamt,    
(phR.hphAdjustmentAmount) as dpmtamt,    
c.customercategory,isnull(c.custgroupname,'')custgroupname,null duedate,'' as chequedetails          
from ahpprocessingheader phA inner join ahpprocessingheader phR    
on phA.hphprocessingid=phR.hphreferenceid and phA.hphdepartmentid=phR.hphdepartmentid     
INNER JOIN acustomermaster c on phr.hphCustomerID=c.CustomerID  
where phA.hphamended=1 and phR.hphreprocessaftersettlement=1 and phR.hphcancel=0    
  

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID: FWL-657960
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwBills')
   DROP view dbo.vwBills
GO

    
-- Modified on  : 05/09/2003    
-- Modified by  : Kishore    
-- Comments     : Changed BillAmount to BillAmount + LcAmount in purchase bill    
-- Modified on  : 05/12/2009    
-- Modified by  : jyothish    
--  change localpurchase bill  amount    
--------------------------------------------------------------------------------    
-- Upgraded by : Regin T.    
-- Upgraded on : 13-08-2010    
--   Local Purchase Bill Amount was corrected.    
--   Since bill discount is already distributed to all items,    
--   discount should not be deducted again.    
--   Old formula: Bill Amount = sum(lpdItemUnitPrice)-(lphdiscount)    
--   New formula: Bill Amount = sum(lpdItemUnitPrice)    
-- Reference: RefNo-1    
--------------------------------------------------------------------------------    
--Altered By Sreejith    
--Altered on 20100827    
--Added the condition ''and  ph.lphConfirmed=1'' to the view to load only confirmed Local Purchase Bills    
---------------------------------------------------------------------------------    
--Modified By : VinothMurugan V.    
--Date    : 14/10/2010    
--Purpose   : Adding interdivision bills    
---------------------------------------------------------------------------------    
--Modified By : Bijesh.b    
--Date    : 04/06/2011    
--Ticket ID   : NML-689759 (Sonee)    
--RefNo.      : RefNo-2    
--Purpose   : For Shop Local Purchase Order, in vendor statement report(accounts)    
--              No need to include discount in Balance amount (in sub report)    
---------------------------------------------------------------------------------    
--Altered By jyothish    
--Altered on 20111018    
--Reference: RefNo-3    
---sum(lpdItemUnitPrice+ISNULL(lpdItemTaxAmount,0))  billamount added    
-----(lphdiscount) is commented    
--------------------------------------------------------------------------------------  
--In urgency it has been altered from client site. Ticket has been raised and need to get update  
--Altered by : Jomin Jose  
---Date : 09/09/2012  
---Reference : Refno-2  
---Purpose :Need to supplier invoiceno in outstanding bill. Now it is showing system generated ref no.  
---I have replaced the column 'lphVendorBillNo' to 'lphVendorInvoiceNo' 
---------------------------------------------------------------------------------------------------------- 
CREATE VIEW [dbo].[vwBills] AS    
-- 1. Head quaters purchase bill    
select b.pbhCompanyID companyid, 0 as shopid, b.pbhDepartmentID departmentid,    
b.pbhBillID billsid, b.pbhVendorID,  b.pbhbillno billsno, b.pbhremarks,    
pbhvendorRefNo referenceno, b.pbhbilldate, b.pbhDueDateforPayment duedate,    
b.pbhBillAmount /* + b.pbhLcAmount */ pbhBillAmount, '0 - 30' as Due,    
'fpb' as type, b.updatetime    
from lospPurchaseBillHeader b    
where b.pbhCashPurchase =0 and b.pbhCancelled = 0 and    
(datediff(dd, b.pbhBillDate, getdate()) between 0 and 30)    
union all    
select b.pbhCompanyID companyid, 0 as shopid, b.pbhDepartmentID departmentid,    
b.pbhBillID billsid, b.pbhVendorID,  b.pbhbillno billsno, b.pbhremarks,    
pbhvendorRefNo referenceno, b.pbhbilldate, b.pbhDueDateforPayment duedate,    
b.pbhBillAmount  /* + b.pbhLcAmount */ pbhBillAmount, '31 - 60' as Due,    
'fpb' as type, b.updatetime    
from lospPurchaseBillHeader b    
where b.pbhCashPurchase =0 and b.pbhCancelled = 0 and    
(datediff(dd, b.pbhBillDate, getdate()) between 31 and 60)    
union all    
select b.pbhCompanyID companyid, 0 as shopid, b.pbhDepartmentID departmentid,    
b.pbhBillID billsid, b.pbhVendorID,  b.pbhbillno billsno, b.pbhremarks,    
pbhvendorRefNo referenceno, b.pbhbilldate, b.pbhDueDateforPayment duedate,    
b.pbhBillAmount  /* + b.pbhLcAmount */ pbhBillAmount, '61 - 90' as Due,    
'fpb' as type, b.updatetime    
from lospPurchaseBillHeader b    
where b.pbhCashPurchase =0 and b.pbhCancelled = 0 and    
(datediff(dd, b.pbhBillDate, getdate()) between 61 and 90)    
union all    
select b.pbhCompanyID companyid, 0 as shopid, b.pbhDepartmentID departmentid,    
b.pbhBillID billsid, b.pbhVendorID,  b.pbhbillno billsno, b.pbhremarks,    
pbhvendorRefNo referenceno, b.pbhbilldate, b.pbhDueDateforPayment duedate,    
b.pbhBillAmount  /* + b.pbhLcAmount */ pbhBillAmount,' > 90' as Due,    
'fpb' as type, b.updatetime    
from lospPurchaseBillHeader b    
where b.pbhCashPurchase =0 and b.pbhCancelled = 0 and    
(datediff(dd, b.pbhBillDate, getdate()) > 90)    
-- 2. shop local purchase bill    
union all    
select ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,    
ph.lphbillno, ph.lphremarks, ph.lphVendorInvoiceNo, ph.lphbilldate, lphDueDateforPayment,    
--sum(lpdItemUnitPrice)  billamount,  -- RefNo-2 commented    
sum(lpdItemUnitPrice+ISNULL(lpdItemTaxAmount,0)),---(lphdiscount),  -- RefNo-2  --RefNo-3    
'0 - 30' as Due, 'lpb' as type, ph.updatetime    
from loslocalpurchaseheader ph,  loslocalpurchasedetail pd    
where ph.lphbillid = pd.lpdbillid and ph.lphshopid = pd.lpdshopid and    
ph.lphcancelled = 0 and  ph.lphConfirmed=1 and ph.lphcashpurchase = 0 and    
(datediff(dd, ph.lphBillDate, getdate()) between 0 and 30)    
group by ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,    
ph.lphbillno, ph.lphremarks, ph.lphVendorInvoiceNo,    
ph.lphbilldate, lphDueDateforPayment, ph.updatetime,lphdiscount    
union all    
select ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,    
ph.lphbillno, ph.lphremarks, ph.lphVendorInvoiceNo, ph.lphbilldate, lphDueDateforPayment,    
--sum(lpdItemUnitPrice) billamount,  -- RefNo-2 commented    
sum(lpdItemUnitPrice+ISNULL(lpdItemTaxAmount,0)), ---(lphdiscount), -- RefNo-2  RefNo-3    
'31 - 60' as Due, 'lpb' as type, ph.updatetime    
from loslocalpurchaseheader ph,  loslocalpurchasedetail pd    
where ph.lphbillid = pd.lpdbillid and ph.lphshopid = pd.lpdshopid and    
ph.lphcancelled = 0 and  ph.lphConfirmed=1 and ph.lphcashpurchase = 0 and    
(datediff(dd, ph.lphBillDate, getdate()) between 31 and 60)    
group by ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,    
ph.lphbillno, ph.lphremarks, ph.lphVendorInvoiceNo,    
ph.lphbilldate, lphDueDateforPayment, ph.updatetime ,lphdiscount    
union all    
select ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,    
ph.lphbillno, ph.lphremarks, ph.lphVendorInvoiceNo, ph.lphbilldate, lphDueDateforPayment,    
--sum(lpdItemUnitPrice) billamount,   -- RefNo-2 commented    
sum(lpdItemUnitPrice+ISNULL(lpdItemTaxAmount,0)),---(lphdiscount),  -- RefNo-2   RefNo-3    
'61 - 90' as Due, 'lpb' as type, ph.updatetime    
from loslocalpurchaseheader ph,  loslocalpurchasedetail pd    
where ph.lphbillid = pd.lpdbillid and ph.lphshopid = pd.lpdshopid and    
ph.lphcancelled = 0 and  ph.lphConfirmed=1 and ph.lphcashpurchase = 0 and    
(datediff(dd, ph.lphBillDate, getdate()) between 61 and 90)    
group by ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,    
ph.lphbillno, ph.lphremarks, ph.lphVendorInvoiceNo,    
ph.lphbilldate, lphDueDateforPayment, ph.updatetime,lphdiscount    
union all    
select ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,    
ph.lphbillno, ph.lphremarks, ph.lphVendorInvoiceNo, ph.lphbilldate, lphDueDateforPayment,    
--sum(lpdItemUnitPrice) billamount,  -- RefNo-2 commented    
sum(lpdItemUnitPrice+ISNULL(lpdItemTaxAmount,0)),---(lphdiscount), -- RefNo-2   RefNo-3    
' > 90' as Due, 'lpb' as type, ph.updatetime    
from loslocalpurchaseheader ph,  loslocalpurchasedetail pd    
where ph.lphbillid = pd.lpdbillid and ph.lphshopid = pd.lpdshopid and    
ph.lphcancelled = 0 and  ph.lphConfirmed=1 and ph.lphcashpurchase = 0 and    
(datediff(dd, ph.lphBillDate, getdate())  > 90)    
group by ph.lphCompanyID, ph.lphshopid, ph.lphDepartmentID, ph.lphBillID, ph.lphVendorID,    
ph.lphbillno, ph.lphremarks, ph.lphVendorInvoiceNo,    
ph.lphbilldate, lphDueDateforPayment, ph.updatetime,lphdiscount    
union all    
-- 3.accounts bill    
select  b.CompanyID, 0 as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, dateadd(dd,b.dueperiod,b.billdate), sum(bd.amount)    
billamount,  '0 - 30' as Due , 'accb' as type, b.updatetime    
from billsdebitdetails bd, bills b    
where b.companyid = bd.companyid and b.billsid = bd.billsid and    
b.cancelled = 0 and b.cashpurchase = 0 and (datediff(dd, b.BillDate, getdate())  between 0 and 30)    
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, b.updatetime, b.dueperiod, b.DepartmentID    
union all    
select  b.CompanyID, 0 as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, dateadd(dd,b.dueperiod,b.billdate), sum(bd.amount)    
billamount, '31 - 60' as Due , 'accb' as type, b.updatetime    
from billsdebitdetails bd, bills b    
where b.companyid = bd.companyid and b.billsid = bd.billsid and    
b.cancelled = 0 and b.cashpurchase = 0 and (datediff(dd, b.BillDate, getdate())  between 31 and 60)    
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, b.updatetime, b.dueperiod, b.DepartmentID    
union all    
select  b.CompanyID, 0 as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, dateadd(dd,b.dueperiod,b.billdate), sum(bd.amount)    
billamount, '61 - 90' as Due , 'accb' as type, b.updatetime    
from billsdebitdetails bd, bills b    
where b.companyid = bd.companyid and b.billsid = bd.billsid and    
b.cancelled = 0 and b.cashpurchase = 0 and (datediff(dd, b.BillDate, getdate())  between 61 and 90)    
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, b.updatetime, b.dueperiod, b.DepartmentID    
union all    
select  b.CompanyID, 0 as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, dateadd(dd,b.dueperiod,b.billdate), sum(bd.Amount)    
billamount, ' > 90' as Due , 'accb' as type, b.updatetime    
from billsdebitdetails bd, bills b    
where b.companyid = bd.companyid and b.billsid = bd.billsid and    
b.cancelled = 0 and b.cashpurchase = 0 and (datediff(dd, b.BillDate, getdate())  > 90)    
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, b.updatetime, b.dueperiod, b.DepartmentID    
union all    
-- 4.credit note    
SELECT dcn.DCNCompanyid, 0 as shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNvendorID,    
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno, dcn.DCNDate, dcn.dcndate,    
DCNAmount,  '0 - 30'  as Due, 'cn' as type, dcn.updatetime    
FROM debitcreditnote dcn    
WHERE dcn.DCNvendorID is not null and dcn.DCNDebit =0 and dcn.DCNCancelled= 0    
and (datediff(dd,  dcn.dcnDate, getdate())  between 0 and 30)    
union all    
SELECT dcn.DCNCompanyid, 0 as shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNvendorID,    
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno, dcn.DCNDate, dcn.dcndate,    
DCNAmount, '31 - 60'  as Due, 'cn' as type, dcn.updatetime    
FROM debitcreditnote dcn    
WHERE dcn.DCNvendorID is not null and dcn.DCNDebit =0 and dcn.DCNCancelled= 0    
and (datediff(dd,  dcn.dcnDate, getdate())  between 31 and 60)    
union all    
SELECT dcn.DCNCompanyid, 0 as shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNvendorID,    
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno, dcn.DCNDate, dcn.dcndate,    
DCNAmount, '61 - 90'  as Due, 'cn' as type, dcn.updatetime    
FROM debitcreditnote dcn    
WHERE dcn.DCNvendorID is not null and dcn.DCNDebit =0 and dcn.DCNCancelled= 0    
and (datediff(dd,  dcn.dcnDate, getdate())  between 61 and 90)    
union all    
SELECT dcn.DCNCompanyid, 0 as shopid, dcn.dcndepartmentid, dcn.DCNId, dcn.DCNvendorID,    
dcn.dcnno, dcn.dcnremarks, dcn.dcnreferenceno, dcn.DCNDate, dcn.dcndate,    
DCNAmount, ' > 90'  as Due, 'cn' as type, dcn.updatetime    
FROM debitcreditnote dcn    
WHERE dcn.DCNvendorID is not null and dcn.DCNDebit =0 and dcn.DCNCancelled= 0    
and (datediff(dd,  dcn.dcnDate, getdate())  > 90)    
union all    
SELECT dcn.losDCNCompanyid, losdcnshopid shopid, dcn.losdcndepartmentid, dcn.losDCNId,    
dcn.losDCNvendorID, dcn.losdcnno, dcn.losdcnremarks, dcn.losreferenceno, dcn.losDCNDate,    
dcn.losdcndate, losDCNAmount, '0 - 30'  as Due,    
'scn' as type, dcn.updatetime FROM losdebitcreditnote dcn    
WHERE dcn.losDCNvendorID is not null and dcn.losDCNDebit =0 and dcn.losDCNCancelled= 0    
and (datediff(dd, dcn.losdcnDate,getdate() ) between 0 and 30)    
union all    
SELECT dcn.losDCNCompanyid, losdcnshopid shopid, dcn.losdcndepartmentid, dcn.losDCNId,    
dcn.losDCNvendorID, dcn.losdcnno, dcn.losdcnremarks, dcn.losreferenceno, dcn.losDCNDate,    
dcn.losdcndate, losDCNAmount, '31 - 60'  as Due,    
'scn' as type, dcn.updatetime FROM losdebitcreditnote dcn    
WHERE dcn.losDCNvendorID is not null and dcn.losDCNDebit =0 and dcn.losDCNCancelled= 0    
and (datediff(dd, dcn.losdcnDate,getdate() ) between 31 and 60)    
union all    
SELECT dcn.losDCNCompanyid, losdcnshopid shopid, dcn.losdcndepartmentid, dcn.losDCNId,    
dcn.losDCNvendorID, dcn.losdcnno, dcn.losdcnremarks, dcn.losreferenceno, dcn.losDCNDate,    
dcn.losdcndate, losDCNAmount, '61 - 90'  as Due,    
'scn' as type, dcn.updatetime FROM losdebitcreditnote dcn    
WHERE dcn.losDCNvendorID is not null and dcn.losDCNDebit =0 and dcn.losDCNCancelled= 0    
and (datediff(dd, dcn.losdcnDate,getdate() ) between 61 and 90)    
union all    
SELECT dcn.losDCNCompanyid, losdcnshopid shopid, dcn.losdcndepartmentid, dcn.losDCNId,    
dcn.losDCNvendorID, dcn.losdcnno, dcn.losdcnremarks, dcn.losreferenceno, dcn.losDCNDate,    
dcn.losdcndate, losDCNAmount, ' > 90'  as Due,    
'scn' as type, dcn.updatetime FROM losdebitcreditnote dcn    
WHERE dcn.losDCNvendorID is not null and dcn.losDCNDebit =0 and dcn.losDCNCancelled= 0    
and (datediff(dd, dcn.losdcnDate,getdate() ) > 90)    
union all    
-- receipt from supplier's considered as bills    
select rh.companyid, 0 shopid, rh.departmentid, rh.receiptid, rh.vendorid, rh.receiptno,    
rh.remarks,cbreferenceno, rh.receiptdate, rh.receiptdate  , rh.customeramount,  '0 - 30' due,    
'rf' type, rh.updatetime    
from receiptvoucherheader rh where rh.cancelled =0 and vendorid is not null    
and (datediff(dd, rh.receiptdate,getdate()) between 0 and 30)    
union all    
select rh.companyid, 0 shopid, rh.departmentid, rh.receiptid, rh.vendorid,    
rh.receiptno, rh.remarks,cbreferenceno, rh.receiptdate, rh.receiptdate ,    
rh.customeramount, '31 - 60' due,  'rf' type, rh.updatetime    
from receiptvoucherheader rh where rh.cancelled =0 and vendorid is not null    
and (datediff(dd, rh.receiptdate,getdate()) between 31 and 60)    
union all    
select rh.companyid, 0 shopid, rh.departmentid, rh.receiptid, rh.vendorid,    
rh.receiptno, rh.remarks,cbreferenceno, rh.receiptdate, rh.receiptdate ,    
rh.customeramount,  '61 - 90' due,  'rf' type, rh.updatetime    
from receiptvoucherheader rh where rh.cancelled =0 and vendorid is not null    
and (datediff(dd, rh.receiptdate,getdate()) between 61 and 90)    
union all    
select rh.companyid, 0 shopid, rh.departmentid, rh.receiptid, rh.vendorid,    
rh.receiptno, rh.remarks,cbreferenceno, rh.receiptdate, rh.receiptdate ,    
rh.customeramount,  ' > 90' due,  'rf' type, rh.updatetime    
from receiptvoucherheader rh where rh.cancelled =0 and vendorid is not null    
and (datediff(dd, rh.receiptdate,getdate()) > 90)    
union all    
-- inter divisional bill    
select  b.CompanyID, 0 as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, dateadd(dd,b.dueperiod,b.billdate), sum(bd.amount)    
billamount,  '0 - 30' as Due , 'IDB' as type, b.updatetime    
from InterDivisionBillsDetails bd, InterDivisionBillsHeader b    
where b.companyid = bd.companyid and b.billsid = bd.billsid and    
b.cancelled = 0 and b.cashpurchase = 0 and (datediff(dd, b.BillDate, getdate())  between 0 and 30)    
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, b.updatetime, b.dueperiod, b.DepartmentID    
union all    
select  b.CompanyID, 0 as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, dateadd(dd,b.dueperiod,b.billdate), sum(bd.amount)    
billamount, '31 - 60' as Due , 'IDB' as type, b.updatetime    
from InterDivisionBillsDetails bd, InterDivisionBillsHeader b    
where b.companyid = bd.companyid and b.billsid = bd.billsid and    
b.cancelled = 0 and b.cashpurchase = 0 and (datediff(dd, b.BillDate, getdate())  between 31 and 60)    
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, b.updatetime, b.dueperiod, b.DepartmentID    
union all    
select  b.CompanyID, 0 as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, dateadd(dd,b.dueperiod,b.billdate), sum(bd.amount)    
billamount, '61 - 90' as Due , 'IDB' as type, b.updatetime    
from InterDivisionBillsDetails bd, InterDivisionBillsHeader b    
where b.companyid = bd.companyid and b.billsid = bd.billsid and    
b.cancelled = 0 and b.cashpurchase = 0 and (datediff(dd, b.BillDate, getdate())  between 61 and 90)    
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, b.updatetime, b.dueperiod, b.DepartmentID    
union all    
select  b.CompanyID, 0 as shopid, b.DepartmentID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, dateadd(dd,b.dueperiod,b.billdate), sum(bd.Amount)    
billamount, ' > 90' as Due , 'IDB' as type, b.updatetime    
from InterDivisionBillsDetails bd, InterDivisionBillsHeader b    
where b.companyid = bd.companyid and b.billsid = bd.billsid and    
b.cancelled = 0 and b.cashpurchase = 0 and (datediff(dd, b.BillDate, getdate())  > 90)    
group by b.CompanyID, b.billsID, b.vendorID,b.billsno,    
b.remarks, b.ReferenceNo, b.billdate, b.updatetime, b.dueperiod, b.DepartmentID


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID: FWL-657960
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
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

USE [adminv2]
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        
--------------------------------------------------------------------------------       
--In urgency it has been altered from client site. Ticket has been raised and need to get update    
--Altered by : Jomin Jose    
---Date : 09/09/2012    
---Purpose :Need to supplier invoiceno in vendor statement for local purchase . Now it is showing system generated ref no.    
---I have replaced the column 'lphVendorBillNo' to 'lphVendorInvoiceNo'    
--------------------------------------------------------------------------------------------------   
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,        
--Modified by Jomin for S&O : Need to show suppiler bill in statements    
 b.lphbillno tno, isnull(b.lphVendorInvoiceNo,'') 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:Update Received from Bijesh For fixing the defect in defect sheet on 20.09.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionWithMarginGSTSeparately')
   DROP view dbo.vwDailySalesCollectionWithMarginGSTSeparately
GO


--Modified on           : 04/09/2004                  
--Modified by           : Hariharan                   
--Comments              : Added LOsAccountsInvoiceHeader                  
--   : Added lnvoiceheader - Id grouping                  
--   : included service details of service boooking invoices                    
--   : Corrected join condition of ashops with LOsAccountsInvoiceHeader                  
--   : Corrected the service invoice query to consider the repinvdtype field                
---------------------------------------------------------------------------------------                        
--Modified on                  : 22/11/2010               
--Modified by                  : Nidheesh P V                
--Comments                     : AddedF&B               
---------------------------------------------------------------------------------------                        
--RefNo        : RefNo-2        
--Modified by  : Bijesh.B        
--Date         : 16/06/2011, 21/06/2011        
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)        
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-3        
--Modified by  : Nidheesh P V       
--Date         : 16/06/2011        
--Comments     : Used -costprice instead of costprice       
--Modified Area: Daily Sales Report      
----------------------------------------------------------------------------------------------            
--RefNo        : RefNo-4      
--Modified by  : Bijesh.B      
--Date         : 29/07/2011      
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong      
--             : since, Special invoice return after desp, reqqty is negative,      
--     -1 is multiplied with reqqty      
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-5        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 19/01/2012  
--Comments     : Modified F&B part.  
----------------------------------------------------------------------------------------------         
----------------------------------------------------------------------------------------------         
--Created by   : Bijesh.B   
--Date         : 29/03/2012  
--Ticket id    : JDJ-400367 (new report (rptdailysalescollectionGSTSeparately) for sonee - GST separation)  
--Comments     : Created new view and report (Copy of vwDailySalesCollectionWithMargin)  
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-6        
--Modified by  : AADYAKUMAR.D.V       
--Date         : 26/06/2012  
--Comments     : Exchage rate multiplication problem in POS  
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B    
--Date         : 07/07/2012  
--Comments     : Corrected Margin value for credit invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-7 
--Date         : 09/07/2012  
--Comments     : Corrected Margin value for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-8 
--Date         : 09/07/2012  
--Comments     : Corrected gst amount for service invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-9
--Date         : 30/07/2012  
--Comments     : Included Other Charges Service Tax in Credit Invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-10
--Date         : 11/08/2012  
--Comments     : Wrong tax amt is showing if same item with different packing type
--               is retuned in GRN
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-10
--Date         : 13/08/2012  
--Comments     : Corrected cost values in GRN in case if return 1 qty out of 2
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-11
--Date         : 16/08/2012  
--Comments     : Corrected credit sales values in case of two items having same type and one
--               normal item with 2 quantities each, and returning only 1 qty in grn.
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-12
--Date         : 17/08/2012  
--Comments     : Corrected credit sales values in case while deleting GRN.
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-13
--Date         : 25/08/2012  
--Comments     : Corrected serive module company wise cash sales figure and Margin
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--Date         : 05/09/2012  
--Comments     : Corrected Pos-Service invoice figures
----------------------------------------------------------------------------------------------       
--RefNo-14
--Modified by  : BIJESH.B   
--Date         : 20/09/2012  
--Comments     : Defect Sheet(-ve figures showing in cash sales if PD cheque enabled
--               cash sales is fully exchanged.)
----------------------------------------------------------------------------------------------       

create VIEW [dbo].[vwDailySalesCollectionWithMarginGSTSeparately] AS                  
Select                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.poshbilldate, convert(numeric(18,8),sum(cashsales)) cashsales,                  
 convert(numeric(18,8),sum(dcashsales)) dcashsales,                   
 convert(numeric(18,8),sum(ccashsales)) ccashsales,                  
 convert(numeric(18,8),sum(creditsales)) creditsales,                  
 convert(numeric(18,8),sum(dcreditsales)) dcreditsales,                   
 convert(numeric(18,8),sum(ccreditsales)) ccreditsales,                   
 convert(numeric(18,8),sum(costvalue)) costvalue,                  
 convert(numeric(18,8),sum(dcostvalue)) dcostvalue,                   
 convert(numeric(18,8),sum(ccostvalue)) ccostvalue,                   
 convert(numeric(18,8),sum(margin)) margin,                  
 convert(numeric(18,8),sum(dmargin)) dmargin, 
 convert(numeric(18,8),sum(cmargin)) cmargin,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid        
 --RefNo-2 start -------------------------        
,convert(numeric(18,8),sum(PdChequeSales)) PdChequeSales,        
convert(numeric(18,8),sum(dPdChequeSales)) dPdChequeSales,        
convert(numeric(18,8),sum(cPdChequeSales)) cPdChequeSales,        
--RefNo-2 ends -------------------------        
convert(numeric(18,8),sum(GSTAmount))GSTAmount,  
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,  
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount  
from                   
 (                  
  select                   
   shopname, poshShopID, poshbilldate,   
   --convert(numeric(18,8),sum(posdunitprice )) cashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)) ccashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dcashsales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8),sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -  
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))))
	 - sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -  
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   departmentname, poshdepartmentid  departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d                   
  where                   
   poshBillid=posdBillid and poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=0 --RefNo-2  if No PD Cheque Amt involved                       
  group by                   
   shopname, departmentname, poshdepartmentid, poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,poshBillid                  
        
--RefNo-2 Start --------------------------------------------        
--CASH + PD CHEQUE -> Taking only cash amount        
union all        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   --convert(numeric(18,8), 
   --sum(posdunitprice )) cashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshdepexrate)) dcashsales, convert(numeric(18,8),                   
   --sum(posdunitprice * poshexchangerate)) ccashsales,        
     
   --convert(numeric(18,8),sum(posdunitprice)-pdCheque.PosBankAmount) cashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) dcashsales,         
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) ccashsales,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,  
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,                   
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
   --(convert(numeric(18,8), sum(posdunitprice))) - sum(posdcostprice*posdquantity) margin,  
   --(convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -                   
   --     sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   --(convert(numeric(18,8),sum(posdunitprice * poshexchangerate))) -   
   --     sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))))) -   
        sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8), sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshdepexrate)) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -   
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,    
            
   departmentname, poshdepartmentid  departmentid                  
   --,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales,   
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dPdChequeSales,  
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) cPdChequeSales  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
  from                   
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved        
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                            
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         

  

  
/*        
union all        
--CASH + PD CHEQUE -> Taking only Cheque amount        
select                   
   shopname, losposheader.poshShopID, poshbilldate,        
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,        
   0.0 creditsales, 0.0 dcreditsales,                   
   0.0 ccreditsales,      
   /*      
   sum(posdcostprice * posdquantity) costvalue,                   
         
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,                   
        
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,                  
        
   (convert(numeric(18,8), sum(posdunitprice ))) -                   
   sum(posdcostprice*posdquantity) margin,      
         
   (convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -   
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin,       
         
   (convert(numeric(18,8), sum(posdunitprice * poshexchangerate))) -       
   sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
   */      
   0.0 costvalue,0.0 dcostvalue,0.0 ccostvalue,       
   0.0 margin,0.0 dmargin,0.0 cmargin,        
   departmentname, poshdepartmentid  departmentid,                  
    pdCheque.PosBankAmount as PdChequeSales,        
   (pdCheque.PosBankAmount * poshdepexrate) as  dPdChequeSales,        
   (pdCheque.PosBankAmount * poshexchangerate) as cPdChequeSales        
  from                
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque                     
  where                   
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND                   
   s.shopid = posdshopid and POSHCANCELLED=0 and                   
   poshDepartmentid = d.departmentid                  
   and isnull(PosPostDate,0)=1 --RefNo-2  if PD Cheque Amt involved          
   and pdCheque.PoshBillID =losposheader.poshbillid      
   and pdCheque.PoshShopID =losposheader.poshShopID                          
  group by                   
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,                  
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount         
--RefNo-2 ends --------------------------------------------        
*/                  
 union all         

--RefNo-9 start commented and added                    
  --select                   
  -- shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
  -- --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
  -- --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
  -- --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
  -- convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,             
  -- convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,             
  -- convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,             
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
  -- convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -       
  -- --sum(isnull(idcostprice*idquantity,0)))) margin,                   
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
  -- --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
  -- --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
  -- --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -             
		-- sum(isnull(idcostprice*idquantity,0)))) margin,             
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		-- (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
  -- (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		--   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
  -- departmentname, ihdepartmentid departmentid                   
  -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
  -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
  -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
  -- convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  --from                   
  -- losinvoiceheader  ih                  
  -- left outer join losinvoicedetail invd                  
  -- on ihInvoiceid=idInvoiceid and ihshopid=idshopid     
  -- left outer join                   
  -- (select                  
  --  ioShopID,ioInvoiceID,sum(ioAmount) ioAmount                  
  -- from                  
  --  losInvoiceOC                   
  -- group by                  
  -- ioShopID,ioInvoiceID) ocd                   
  -- on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
  -- ashops s, adepartmentmaster d                   
  --where                   
  -- IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and       
  -- ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  --group by                   
  -- shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
  -- ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
    
  
   --credit invoice
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) creditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihexchangerate) ccreditsales,             

   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -      
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,  
                    
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) -             
		 sum(isnull(idcostprice*idquantity,0)))) margin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihexchangerate -             
		   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from          
    
     losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid
   
   union all
   
   --Other Charges
   
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   
   convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) creditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate) ccreditsales,             

   0 costvalue,                   
   0 dcostvalue,                  
   0 ccostvalue,                  
                    
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))Margin,            
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))* ihdepexrate  dmargin,             
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))) * ihexchangerate cmargin,  
   
 departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2       
   
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihexchangerate)cGSTAmount  
  
  from          
     losinvoiceheader  ih                  
   --left outer join losinvoicedetail invd  on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join losInvoiceOC ocd  on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID         
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by  
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid,ocd.ioShopID,ocd.ioInvoiceID
--RefNo-9 ends

 union all                  
                  
  select                   
   shopname, ihShopID, ihinvoicedate,                  
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) Cashsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,         
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,                   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,             
   0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -                   
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,                   
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -             
		sum(isnull(idcostprice*idquantity,0)))) margin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,             
 (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0))) * ihexchangerate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,  
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
 ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from                   
   losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   left outer join                   
   (select                  
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount        
   from                  
    losInvoiceOC                   
   group by                  
   ioShopID,ioInvoiceID) ocd                   
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,                   
   ashops s, adepartmentmaster d                   
  where                   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=1 and ihdepartmentid = d.departmentid and ihtype ='i'                  
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount                  
                  
 union all                  
   select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),sum(sedunitprice * sehexchangerate)) ccashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
   0.0 creditsales,0.0 dcreditsales , 0.0 ccreditsales , sum(sedcostprice * sedquantity) costvalue,                  
   sum(sedcostprice * sedquantity) * sehdepexrate dcostvalue,                   
   sum(sedcostprice * sedquantity) * sehexchangerate ccostvalue,                  
   --convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedquantity) margin,  
   --convert(numeric(18,8), sum(sedunitprice* sehdepexrate)) -                   
 --sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   --convert(numeric(18,8), sum(sedunitprice * sehexchangerate )) -   
   --sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) - sum(sedcostprice * sedquantity) margin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) -                   
          sum(sedcostprice * sedquantity) * sehdepexrate dmargin,  
   convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) -   
          sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,  
    departmentname, sehdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d            
  where          
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and              
   sedbillorexchange = 'E' and sehshopid = shopid and sehdepartmentid = d.departmentid          
  group by      
   shopname, sehshopid, departmentname, sehdepartmentid, sehexchangedate ,                  
   departmentname,sehdepexrate, sehexchangerate,sehExchangeID                  
 union all                  
       
 -- RefNo-4 start  commented below      
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  sum(idunitprice )) cashsales, convert(numeric(18,8),                   
 ------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,8),                   
 ------  sum(idunitprice * ihexchangerate)) ccashsales,                  
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  (convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                   
 ------  (convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                   
 ------  (convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin, departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  ihdepartmentid =d.departmentid and idratetype=0 and ihproforma=0 and                   
 ------  ihshopid = shopid and ihcashinvoice=1 and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, departmentname, ihdepartmentid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
 ------ union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                   
 ------  0.0 ccashsales, convert(numeric(18,8), sum(idunitprice )) creditsales,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate)) dcreditsales,          
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate)) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                  
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                  
 ------  convert(numeric(18,8), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,                   
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate) - sum(idcostprice*reqqty) * ihexchangerate) cmargin,                   
 ------  departmentname, ihDepartmentId departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and                   
 ------  idratetype=0 and ihproforma=0 and ihshopid = shopid and                   
 ------  ihcashinvoice=0 and ihDepartmentId = d.departmentid                  
 ------  and ihTransfinished = 1                  
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname, ihinvoicedate ,                   
 ------  ihexchangerate, ihdepexrate,ihInvoiceid   
               
 ------union all                  
 -- RefNo-4 ends      
                  
  select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),-sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehexchangerate)) ccashsales,                  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dcashsales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) ccashsales,  
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(-sedcostprice * sedExchangeQty) costvalue,    --RefNo-3              
   sum(-sedcostprice * sedExchangeQty) * sehdepexrate dcostvalue, sum(-sedcostprice * sedExchangeQty)     --RefNo-3             
   * sehexchangerate ccostvalue,  
    ---(convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedExchangeQty)) margin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -                   
   --    sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -   
    --    sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
           sum(sedcostprice * sedExchangeQty)) margin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -                   
        sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
        sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
  
   departmentname, sehdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d                   
    ,LOsPosHeader ph   
  where        
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid                   
   and sehdepartmentid = d.departmentid 
  and ph.poshBillID=losposexchangeheader.sehBillID  --RefNo-14
  and ph.poshShopID= losposexchangeheader.sehShopID and  isnull(PosPostDate,0)=0 --RefNo-14
  group by                   
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,                  
   sehdepexrate,sedExchangeid                  
 union all       
--RefNo-14 start

 select                   
   shopname, sehshopid, sehexchangedate,  
   --convert(numeric(18,8),-sum(sedunitprice )) cashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehdepexrate)) dcashsales,  
   --convert(numeric(18,8),-sum(sedunitprice * sehexchangerate)) ccashsales,                  
   0 cashsales, 0 dcashsales, 0 ccashsales,
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(-sedcostprice * sedExchangeQty) costvalue,    --RefNo-3              
   sum(-sedcostprice * sedExchangeQty) * sehdepexrate dcostvalue, sum(-sedcostprice * sedExchangeQty)     --RefNo-3             
   * sehexchangerate ccostvalue,  
    ---(convert(numeric(18,8), sum(sedunitprice)) - sum(sedcostprice * sedExchangeQty)) margin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -                   
   --    sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    ---(convert(numeric(18,8), sum(sedunitprice )) -   
    --    sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
           sum(sedcostprice * sedExchangeQty)) margin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -                   
        sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,  
    -(convert(numeric(18,8), sum((sedunitprice-isnull(sedItemTaxAmount,0)))) -   
        sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                   
  
   departmentname, sehdepartmentid departmentid,                  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) PdChequeSales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) dPdChequeSales,  
   convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) cPdChequeSales,  
     
   convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
    convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount  
  from                   
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d                   
    ,LOsPosHeader ph   
  where        
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and                   
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid                   
   and sehdepartmentid = d.departmentid 
  and ph.poshBillID=losposexchangeheader.sehBillID  --RefNo-14
  and ph.poshShopID= losposexchangeheader.sehShopID and  isnull(PosPostDate,0)=1 --RefNo-14
  group by                   
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,                  
   sehdepexrate,sedExchangeid         
--RefNo-14 ends
 union all       
       
 -- RefNo-4 start                  
 ------ --gave idratetype condition for special invoice return                  
 ------ --special invoice return - cash                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),                   
 ------  -(sum(idunitprice ))) cashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,8),                   
 ------  -(sum(idunitprice * ihexchangerate))) ccashsales,                   
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(idcostprice * abs(reqqty)) costvalue,                   
 ------  sum(idcostprice * abs(reqqty)) * ihdepexrate dcostvalue, sum(idcostprice * abs(reqqty)) *                   
 ------  ihexchangerate ccostvalue,  -((convert(numeric(18,8), sum(idunitprice ))) -            
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0                    
 ------  and ihproforma=0 and ihshopid = shopid and ihTransfinished = 1                   
 ------  and ihcashinvoice=1 AND IDratetype=1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihdepartmentid, departmentname, ihshopid,                   
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid                  
          
 ------union all                  
 ------ --special invoice return - credit                  
 ------ select                   
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice ))) creditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihdepexrate))) dcreditsales,                   
 ------  -(convert(numeric(18,8), sum(idunitprice * ihexchangerate))) ccreditsales,                   
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,                   
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                   
 ------  -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -                   
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8),                   
 ------  sum(idunitprice ))) -  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,                   
 ------  departmentname, ihdepartmentid departmentid                   
 ------  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ------ from                   
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,                   
 ------  adepartmentmaster d                   
 ------ where                   
 ------  ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND  
 ------  IHCANCELLED = 0 and ihproforma = 0 and ihshopid = shopid and                   
 ------  ihcashinvoice = 0 and idratetype = 1 and ihtransfinished = 1 and                   
 ------  ihdepartmentid = d.departmentid                   
 ------ group by                   
 ------  shopname, ihshopid, ihdepartmentid, departmentname,                  
 ------  ihinvoicedate , ihexchangerate, ihdepexrate,ihInvoiceid                  
                  
 ------union all                  
      
-- special Invoice (cash)        
select         
shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccashsales,    
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,  
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales,   
  
0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty) margin,             
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,        
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty))* ihexchangerate cmargin,  
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d   
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                    
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all                                      
      
-------- special invoice - return before despatch                          
select shopname,                                     
  ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,       
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-sum(idcostprice * reqqty) costvalue ,      
-sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
-sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
     
union all                                      
                                   
-- Special invoice return  - after desp                  
select shopname,                                     
 ihshopid, ihinvoicedate,                  
 --convert(numeric(18,8),-sum(idUnitPrice)) cashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcashsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccashsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,     
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                      
--sum(idcostprice * reqqty) costvalue,      
--sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
--sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                        
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1         
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
-- special Invoice (credit)      
union all      
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) ccreditsales,    
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
       
 sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,      
--(convert(numeric(18,8), sum(idunitprice)))-sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))))-sum(idcostprice*reqqty) margin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                                       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                      
 and IhTransFinished = 1 And ihcAshinvoice <>1 and ihNoofOCDetails=0       
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                             
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                   
union all         
      
-- special invoice - return before despatch                          
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,                 
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) ccreditsales,     
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,  
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
  
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
 -sum(idcostprice * reqqty) costvalue ,      
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,      
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) margin,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
- --(convert(numeric(18,8), sum(idunitprice))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
  
from                                       
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where       
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice <>1 and ihTransFinished = 1       
 and ihNoofOCDetails<>0          
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                               
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
                                          
union all                                      
                                   
-- Special invoice return  - after desp                                    
select         
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,  
  0.0 ccashsales,       
 --convert(numeric(18,8),-sum(idUnitPrice)) creditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate))dcreditsales,      
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate))ccreditsales,       
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)dcreditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)ccreditsales,       
-- sum(idcostprice * reqqty) costvalue,      
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,      
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,                 
--(convert(numeric(18,8), sum(idunitprice))) - sum(idcostprice*reqqty) margin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
sum(idcostprice * reqqty) costvalue,      
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  ,       
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) margin,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
--idUnitPrice, idItemTaxAmount  
departmentname, ihdepartmentid departmentid               
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2      
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount   
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount  
from                                       
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                       
where                
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                       
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice <>1                                     
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID        
Group By        
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,           
 ihdepexrate, ihexchangerate      
      
 -- RefNo-4 ends       
  union all                 

-- RefNo-10 start commented below and added
  --select                   
  -- shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) creditsales,                   
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                   
  -- -convert(numeric(18,8), (sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   

  -- -sum(grncostprice*grndquantity) costvalue,
  -- - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                  
  -- -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,                   

  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))))-  
  --         sum(grncostprice*grndquantity)) margin,  
  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -                   
  --     sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
  -- -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -  
  --      sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,
                           
  -- departmentname, grnhdepartmentid departmentid                  
  -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
  -- ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
  -- ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
  --  -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  --from                   
  -- losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d                   
  --where               
  -- GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0               
  -- and grnhshopid = shopid and grnhdepartmentid = d.departmentid                   
  --group by                   
  -- shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname, 
  -- grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID                  

select                   
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) creditsales,                   
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))) * grnhdepexRate) dcreditsales,                 
   -convert(numeric(18,8), (sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))) * grnhExchangeRate) ccreditsales,   
   -- -sum(grncostprice*grndquantity) costvalue,
   -- -sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,                  
   -- -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,  
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))costvalue,
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))* grnhdepexrate dcostvalue,                  
   -sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))* grnhexchangerate ccostvalue,  

   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))))-  
           sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))) margin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) -                   
       sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity)))* grnhdepexRate dmargin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))))) -  
        sum(grncostprice*((invd.idquantity/idPQuantity)*grndquantity))) * grnhExchangeRate cmargin,                   

   departmentname, grnhdepartmentid departmentid                  
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
   ,-convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))GSTAmount  
   ,-convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
    -convert(numeric(18,8),sum(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
  from losgoodsreturnnoteheader 
   inner join losgoodsreturnnotedetail on  GrnhGoodsreturnnoteID = GRNDReturnNoteID 
		and grnhShopid = GRNDShopid
   inner join ashops s on  grnhshopid = shopid
   inner join adepartmentmaster d  on grnhdepartmentid = d.departmentid                   
   -- below linking with credit invoice was used since
   -- qty based on packing type was not available in GRN table
   left join  losinvoiceheader  ih on ih.ihInvoiceID = losgoodsreturnnoteheader.GrnhInvoiceID
		and ih.ihShopID = losgoodsreturnnoteheader.grnhShopid 
		and IHCANCELLED=0 and ihproforma=0 and ihshopid = s.shopid and    --RefNo-12 added                  
		ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'   --RefNo-12 added
		
   left outer join losinvoicedetail invd on ihInvoiceid=idInvoiceid and ihshopid=idshopid 
		and invd.idItemID = losgoodsreturnnotedetail.GRNDItemID --RefNo-11
		and invd.idPackingTypeID = losgoodsreturnnotedetail.grndPackTypeId
		and invd.idShopID = losgoodsreturnnotedetail.GRNDShopid
  where 
	   GrnhCancel =0                   
  group by                   
		shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,                   
		grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID 

-- RefNo-10 ends

  --hari added to include the service booking invoice parts replaced items                  
 UNION ALL                  
  
  --service invoice (cash)                
  select                   
   shopname, repinvdshopid, serinvhdate,  
   --convert(numeric(18,8),sum(repinvdrate* repinvdqty)) cashsales,  
   --convert(numeric(18,8),sum(repinvdrate* seinvhdepexrate * repinvdqty)) dcashsales,  
   --convert(numeric(18,8),sum(repinvdrate* serinvhcmpexrate * repinvdqty)) ccashsales,                  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales,    
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales,   --RefNo-13                 

   0.0 creditsales, 0.0 dcreditsales , 0.0 ccreditsales ,  sum(repinvdcostprice * repinvdqty) costvalue,                   
   sum(repinvdcostprice * repinvdqty) * seinvhdepexrate  dcostvalue,  
   sum(repinvdcostprice * repinvdqty) *serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -  
   --  sum(repinvdcostprice * repinvdqty),                   
   --convert(numeric(18,8),(sum(repinvdrate * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,   
   --convert(numeric(18,8),(sum(repinvdrate  * repinvdqty))) -   
   -- sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty)margin,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))  
      -sum(repinvdcostprice * repinvdqty)) *  seinvhdepexrate dmargin,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))  
 -sum(repinvdcostprice * repinvdqty)) *  serinvhcmpexrate cmargin,          
  
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --RefNo-8  start commneted, since this gst amount is taken care in below
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
 --convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
   ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
--RefNo-8 ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d                   
  where                   
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1                  
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, serinvhDepartmentid,                   
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid                   
                  
 union all                  
 
  --service Details  (cash)                
  select                   
   shopname, serinvhshopid, serinvhdate,  
   --convert(numeric(18,8) , serinvhserviceamt) cashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcashsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccashsales ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales ,  --RefNo-13 changed bracket         
  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                       
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,           
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,    
   
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)),          
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,       
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) *  serinvhcmpexrate) ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales ,             

   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount  
  from                   
--RefNo-8 start commented below
   --losserviceinvheader, ashops s, adepartmentmaster d                   
	 --where                   
	 --  serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1         
	 --  and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid                  
   
 losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid   and Patindex('%y%',repinvdtype)>0 
 where                   
	serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1  
    and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends 
 union all
  
  --service invoice (credit)	    
    select                   
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , (sum(repinvdrate* repinvdqty))) creditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * seinvhdepexrate * repinvdqty))) dcreditsales ,                   
   --convert(numeric(18,8) , (sum(repinvdrate * serinvhcmpexrate * repinvdqty))) ccreditsales ,   
  
   convert(numeric(18,8),(sum( (repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccreditsales ,             
                     
   sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*                   
   seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,                   
     
   --convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty), convert(numeric(18,8) , ( sum(repinvdrate * repinvdqty))) -                  
   --sum(repinvdcostprice * repinvdqty) * seinvhdepexrate , convert(numeric(18,8) ,                   
   --( sum(repinvdrate * repinvdqty))) - sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate ,                   
   
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))-sum(repinvdcostprice * repinvdqty)) * seinvhdepexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))-sum(repinvdcostprice * repinvdqty)) * serinvhcmpexrate,  

   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  --RefNo-8  start commneted, since this gst amount is taken care in below
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount  
	 --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,  
	 -- convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount  
	,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
  --RefNo-8  ends
  from                   
   losinvoicedpartsreplacedetails, losserviceinvheader,                   
   ashops s, adepartmentmaster d 
  where 
   serinvhid = repinvinvoiceid and                   
   serinvhshopid = repinvdshopid AND serinvhcancelled=0                   
    and repinvdshopid = shopid and serinvhcashacc is null                   
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid                    
   and Patindex('%y%',repinvdtype)>0                
  group by                   
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,                  
   serinvhcmpexrate ,serinvhid   
   
   union all
          
  --service Details   (credit)               
  select                   
 shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8) , serinvhserviceamt) creditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) dcreditsales ,                   
   --convert(numeric(18,8) , serinvhserviceamt * serinvhcmpexrate) ccreditsales ,     
   
   --RefNo-8 start commented below
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) creditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate) dcreditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate) ccreditsales ,             
   convert(numeric(18,8),serinvhserviceamt- (isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) creditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcreditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccreditsales ,             
   --RefNo-8 ends
   
   0 costvalue, 0 dcostvalue, 0 ccostvalue,                   
   --convert(numeric(18,8) , serinvhserviceamt) ,                   
   --convert(numeric(18,8) , serinvhserviceamt * seinvhdepexrate) ,                   
   --convert(numeric(18,8) ,  serinvhserviceamt *  serinvhcmpexrate) ,                   
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))*seinvhdepexrate ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))*serinvhcmpexrate ,             
   departmentname, serinvhDepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2     
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount  
 ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,  
 convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount    
  from                   
  --RefNo-8 start commented below
  -- losserviceinvheader, ashops s, adepartmentmaster d                   
  --where                   
  -- serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid           
  losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0 
 where                   
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-8 ends
   
  union all                  


  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002                  
  --credit           
  select           
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,                   
   0.0 ccashsales,                  
    convert(numeric(18,8), sum(redunitprice)) creditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehdepexrate)  dcreditsales,                   
   convert(numeric(18,8), sum(redunitprice) * rehexchangerate) ccreditsales,
   sum(redcostprice * redquantity) costvalue,                   
   sum(redcostprice * redquantity) * rehdepexrate dcostvalue, 
   sum(redcostprice * redquantity) * rehexchangerate ccostvalue,
   (convert(numeric(18,8), sum(redunitprice ))) -  sum(redcostprice * redquantity) margin,
   (convert(numeric(18,8), sum(redunitprice * rehdepexrate))) -                   
		sum(redcostprice * redquantity) * rehdepexrate dmargin,
   (convert(numeric(18,8), sum(redunitprice * rehexchangerate))) - 
		sum(redcostprice * redquantity) * rehexchangerate cmargin,                   
   departmentname, rehdepartmentid                  
 ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 ,0,0,0  
  from                   
   losExportDetail, losExportHeader, ashops s, adepartmentmaster d                   
  where                   
   rehExportID = redExportID and rehshopid = redshopid AND                   
   reHCANCELLED=0 and rehtype ='i' and                  
   rehproforma=0 and rehshopid = shopid and rehcashinvoice=0 and                   
   rehdepartmentid = d.departmentid                   
  group by                   
   shopname, rehshopid, departmentname, rehdepartmentid, rehExportDate,                   
   rehdepexrate, rehexchangerate,rehExportID                   
            
 union all                  
 -- added From Vwcashsales -Margin Not calculating                  
                   
 select                   
  s.shopname, vws.sishopid, vws.siinvoicedate,                   
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,                   
  convert(numeric(18,8),sum(vws.sidamount)) as  dcashsales,  -- RefNo-7 corrected amount                  
  convert(numeric(18,8),sum(vws.sicamount)) as ccashsales,   -- RefNo-7 corrected amount                                  
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
   0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
  convert(numeric(18,8),sum(vws.siamount))as margin,    -- RefNo-7 included  -vws.GSTAmount                              
  convert(numeric(18,8),sum(vws.sidamount))as  dmargin,    -- RefNo-7 included  -vws.GSTAmount                               
  convert(numeric(18,8),sum(vws.sicamount))as cmargin,  -- RefNo-7 included  -vws.GSTAmount          
  d.departmentname,lah.aidepartmentid  departmentid                   
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
  , sum(vws.dGSTAmount)as dGSTAmount  
  , sum(vws.cGSTAmount)as cGSTAmount  
 from                   
  vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d ,ashops s                  
 where                   
  aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
  aishopid = sishopid and lah.aicashinvoice=1 and       
  lah.aidepartmentid =d.departmentid and s.departmentid = d.departmentid                  
  and aiShopId = s.ShopId                  
 group by                   
  s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid, vws.siinvoicedate                  
  ,aidepexrate, aiexchangerate        
 union all                  
                  
    select s.shopname, vws.sishopid, vws.siinvoicedate,                   
    0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                   
    convert(numeric(18,8),sum(vws.siamount))as creditsales,                   
    convert(numeric(18,8),sum(vws.sidamount))as dcreditsales, -- RefNo-7 corrected amount                   
    convert(numeric(18,8),sum(vws.sicamount))as ccreditsales, -- RefNo-7 corrected amount                                    
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                  
    convert(numeric(18,8),sum(vws.siamount)) as margin,    -- RefNo-7 included  -vws.GSTAmount              
    convert(numeric(18,8),sum(vws.sidamount)) as dmargin,  -- RefNo-7 included  -vws.GSTAmount               
convert(numeric(18,8),sum(vws.sicamount)) as cmargin,  -- RefNo-7 included  -vws.GSTAmount   
    d.departmentname,lah.aidepartmentid  departmentid                   
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
  , sum(vws.GSTAmount)as GSTAmount  
    , sum(vws.dGSTAmount)as dGSTAmount  
    , sum(vws.cGSTAmount)as cGSTAmount  
    from vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d,ashops s      
    where aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and                   
    aishopid = sishopid and lah.aicashinvoice=0 and lah.aidepartmentid =d.departmentid                  
    and s.departmentid = d.departmentid and s.ShopId = aiShopId group by                       
    s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid,vws.siinvoicedate,aiinvoiceid,
    aidepexrate                   
                   
    UniOn All -- added from vwCashSales                 
    --Shop debit credit notes and handling debit notes which are debit to the                
    -- customer and hence act as invoices to be settled                      
    Select  s.shopname,losdcnshopid,losdcndate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                  
    COnvert(numeric(18,8),Sum(losDCNAmount))  creditsales,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dcreditsales,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  ccreditsales,               
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    COnvert(numeric(18,8),Sum(losDCNAmount))  margin,                     
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dmargin,               
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  cmargin,              
 d.departmentname,losdcndepartmentid                   
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2    
       ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount      
    From Ashops s,  losdebitcreditnote, adepartmentmaster d               
    Where  s.shopid = losdcnshopid And s.accountable Is Not Null                   
    And d.DepartmentID = losdcndepartmentid And losdcncancelled =0                    
    And losdcndebit =1  Group By s.shopname,d.departmentname,losdcnshopid,                  
    losdcndate, losdepexrate, losexchangerate,losdcndepartmentid           
              
    --hq serivce invoice dOne for shop                    
    Union all              
               
    Select  null, 0,ai.invoicedate,              
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,          
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  creditsales,             
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dcreditsales,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  ccreditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)ccreditsales,         
  
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                           
    --COnvert(numeric(18,8),Sum(serviceqty * amount))  margin,                     
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate)  dmargin,               
    --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate)  cmargin,   
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,               
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,         
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)) * exchangerate)cmargin,        
                 
    d.departmentname,ai.departmentid           
     ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
     ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount   
     ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,  
      convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount  
  
  From accountsinvoiceheader ai, serviceinvoicedetails ser ,adepartmentmaster d              
    Where ai.invoiceid = ser.invoiceid And ai.companyid =                     
    ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0             
    and ai.departmentid = d.departmentid and ai.companyid = d.companyid               
    Group By  ai.invoicedate,depexrate,exchangerate,              
    d.departmentname,ai.departmentid              
        
  
 ----F&B---------------------------   
 --RefNo-5----------------------------------------------start----------------------------------------------------------------------------  
 ----------------------------------------  
 -- select v.* from        
 --(        
--select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales, 
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 --convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 --inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 --UNION ALL        
        
 --select DISTINCT s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end Cashsales,        
 --case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end DepCashsales,        
 -- case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --   when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
 --   when poshBillType='VCA' then 0.00 end ComCashsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID)))        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00  
--when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end Creditsales,        
 --   case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshdepexrate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end DepCreditsales,        
 --case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID))*poshExchangeRate)        
 --when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 --when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 --   when poshBillType='VCR' then 0.00 end ComCreditsales,        
 --sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshdepexrate))dcostprice,        
 --convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID))*poshExchangeRate))ccostprice,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))margin,        
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshdepexrate))dmargin,   
 --convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 --d.departmentname[deptname],poshDepartmentid[deptid]        
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2        
 --from losposfandbheader fh inner join Fb_processdetail fd on        
 --poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 --poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 --inner join aitem a on a.itemid=fb_pd_dishid        
 --inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 --where fb_pd_AddedItemtype=2        
 --)v       
  
/*  
union all  
  select shopname,poshShopID,poshBillDate,Cashsales,DepCashsales,ComCashsales,Creditsales,DepCreditsales,  
 ComCreditsales,costprice,dcostprice,ccostprice,margin,dmargin,cmargin,deptname,deptid,  
PdChequeSales,dPdChequeSales,cPdChequeSales  from  
 (        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid) costprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),((poshbillamount)-((sum(dd.fb_dd_dishcp)over(partition by fb_dd_dishid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2        
  fb_pd_processdetailid  
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=0  --for ingredients        
 inner join FB_Dishdetails dd on fb_dd_dishid=fb_pd_dishid and dd.fb_dd_companyid=fb_pd_companyid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
        
 UNION ALL        
        
 select DISTINCT poshBillNo,fb_pd_dishid,s.shopname,poshShopID,dateadd(dd,0, datediff(dd,0, poshBillDate))poshBillDate,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end Cashsales,        
 case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00  when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end DepCashsales,        
  case when poshBillType='CA' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
    when poshBillType='CR' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCR' then 0.00         
    when poshBillType='VCA' then 0.00 end ComCashsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid)))        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
 when poshBillType='VCR' then 0.00 end Creditsales,        
    case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end DepCreditsales,        
 case when poshBillType='CR' then COnvert(numeric(18,8),(sum(fb_pd_Rate*fb_pd_reusedqty)over (partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate)        
 when poshBillType='CA' then 0.00 when poshBillType='VO' then 0.00         
 when poshBillType='NP' then 0.00 when poshBillType='VCA' then 0.00         
    when poshBillType='VCR' then 0.00 end ComCreditsales,        
 sum(a.itemrate)over(partition by a.itemid,poshBillID) costprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshdepexrate))dcostprice,        
 convert(numeric(18,8),((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*poshExchangeRate))ccostprice,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))margin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshdepexrate))dmargin,        
 convert(numeric(18,8),(poshbillamount-((sum(a.itemrate)over(partition by a.itemid,poshBillID,fb_pd_processdetailid))*fb_pd_reusedqty)*poshExchangeRate))cmargin,        
 d.departmentname[deptname],poshDepartmentid[deptid]        
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales, --RefNo-2   
  fb_pd_processdetailid       
 from losposfandbheader fh inner join Fb_processdetail fd on        
 poshShopID=fb_pd_outletid and poshBillID=fb_pd_processid and         
 poshCompanyID=fb_pd_companyid and poshCancelled=0 and fb_pd_AddedItemtype=2  --for dish adds        
 inner join aitem a on a.itemid=fb_pd_dishid        
 inner join ashops s on shopid=poshShopID inner join adepartmentmaster d on poshDepartmentid=d.departmentid        
 where fb_pd_AddedItemtype=2        
  
  
 )  
  
  v        
 --RefNo-5----------------------------------------------end----------------------------------------------------------------------------  
  ----------------------------------------                  
  */  
     
 )cashcreditcollection      
group by                   
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,                   
 cashcreditcollection.departmentname, cashcreditcollection.departmentid,                   
 cashcreditcollection.poshbilldate   
  

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Daily Sales and Returns GST Separately by bijesh on 25.09.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionWithMarginDetWithOutGST')
   DROP view dbo.vwDailySalesCollectionWithMarginDetWithOutGST
GO


---Created ON :13/01/2008
---Comments   :For Daily Sales With Returns Report   
---------------------------------------------------------------------------------------                
--RefNo        : RefNo-2
--Modified by  : Bijesh.B
--Date         : 21/06/2011
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-3
--Modified by  : Bijesh.B
--Date         : 29/07/2011
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong
--             : since, Special invoice return after desp, reqqty is negative,
--				 -1 is multiplied with reqqty
----------------------------------------------------------------------------------------------   
--RefNo        : Newly created view (copy of vwDailySalesCollectionWithMarginDet)
--Modified by  : Bijesh.B
--Date         : 13/03/2012
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Need to show GST separately
----------------------------------------------------------------------------------------------   
--RefNo-4
--Modified by  : Bijesh.B
--Date         : 13/07/2012
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Need to show GST separately - corrected values
----------------------------------------------------------------------------------------------   
--Modified by  : BIJESH.B   
--RefNo        : RefNo-5
--Date         : 01/08/2012  
--Comments     : Corrected Other Charges Service Tax in Credit Invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-6
--Date         : 25/09/2012  
--Comments     : Corrected Dept Margin in case of dollar a/c,
--               GST amt incase of goods return
----------------------------------------------------------------------------------------------       

create VIEW [dbo].[vwDailySalesCollectionWithMarginDetWithOutGST] AS          
Select           
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,           
 cashcreditcollection.poshbilldate, 
 convert(numeric(18,8),sum(cashsales)) cashsales,          
 convert(numeric(18,8),sum(dcashsales)) dcashsales,           
 convert(numeric(18,8),sum(ccashsales)) ccashsales,          
 convert(numeric(18,8),sum(creditsales)) creditsales,          
 convert(numeric(18,8),sum(dcreditsales)) dcreditsales,           
 convert(numeric(18,8),sum(ccreditsales)) ccreditsales,           
 convert(numeric(18,8),sum(costvalue)) costvalue,          
 convert(numeric(18,8),sum(dcostvalue)) dcostvalue,           
 convert(numeric(18,8),sum(ccostvalue)) ccostvalue,           
 convert(numeric(18,8),sum(margin)) margin,          
 convert(numeric(18,8),sum(dmargin)) dmargin,           
 convert(numeric(18,8),sum(cmargin)) cmargin,
 convert(numeric(18,8),sum(Exchange)) Exchange,          
 convert(numeric(18,8),sum(dExchange)) dExchange,           
 convert(numeric(18,8),sum(cExchange)) cExchange,
 convert(numeric(18,8),sum(GReturn)) GReturn,          
 convert(numeric(18,8),sum(dGReturn)) dGReturn,           
 convert(numeric(18,8),sum(cGReturn)) cGReturn,           
 cashcreditcollection.departmentname, cashcreditcollection.departmentid           
--RefNo-2 start -------------------------
,convert(numeric(18,8),sum(PdChequeSales)) PdChequeSales,
convert(numeric(18,8),sum(dPdChequeSales)) dPdChequeSales,
convert(numeric(18,8),sum(cPdChequeSales)) cPdChequeSales,
--RefNo-2 ends -------------------------
convert(numeric(18,8),sum(GSTAmount))GSTAmount,
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount

from           
 (          
  select           
   shopname, losposheader.poshShopID, poshbilldate, 
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales, 
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dcashsales,
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) ccashsales,
   0.0 creditsales, 0.0 dcreditsales,0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,           
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,           
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,          
	(convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))))
	 - sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -  
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
 
   0.00 Exchange,0.00 dExchange,0.00 cExchange,0.00 GReturn,0.00 dGReturn,0.00 cGReturn,
   departmentname, poshdepartmentid  departmentid          
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount
  from           
   losposdetail, losposheader, ashops s, adepartmentmaster d           
  where           
   poshBillid=posdBillid and poshShopid=posdshopid AND           
   s.shopid = posdshopid and POSHCANCELLED=0 and           
   poshDepartmentid = d.departmentid          
   and isnull(PosPostDate,0)=0 --RefNo-2  if No PD Cheque Amt involved                       
  group by           
   shopname, departmentname, poshdepartmentid, poshshopid, poshbilldate, 
   poshdepexrate, poshexchangerate,poshBillid          
     
--RefNo-2 Start --------------------------------------------
 --CASH + PD CHEQUE -> Taking only cash amount
union all
select           
   shopname, losposheader.poshShopID, poshbilldate, 
   --convert(numeric(18,8),sum(posdunitprice )) cashsales, 
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)) dcashsales, 
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)) ccashsales,

   --convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))-pdCheque.PosBankAmount) cashsales, 
   --convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshdepexrate)-pdCheque.PosBankAmount) dcashsales, 
   --convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshexchangerate)-pdCheque.PosBankAmount) ccashsales,
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,
   0.0 creditsales, 0.0 dcreditsales,           
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,           
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,           
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,          

	(convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))))
	 - sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -  
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   

   0.00 Exchange,0.00 dExchange,0.00 cExchange,0.00 GReturn,0.00 dGReturn,0.00 cGReturn,departmentname, poshdepartmentid  departmentid          
   --,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales, 
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dPdChequeSales,
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) cPdChequeSales
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount

  from           
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque           
  where           
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND           
   s.shopid = posdshopid and POSHCANCELLED=0 and           
   poshDepartmentid = d.departmentid 
   and isnull(PosPostDate,0)=1 --if PD Cheque Amt is involved  
   and pdCheque.PoshBillID =losposheader.poshbillid
   and pdCheque.PoshShopID =losposheader.poshShopID            
  group by           
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,          
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount          

/*
union all
 --CASH + PD CHEQUE -> Taking only Cheque amount
 select           
   shopname, losposheader.poshShopID, poshbilldate, 
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,
   0.0 creditsales, 0.0 dcreditsales,           
   0.0 ccreditsales,
   /*
   sum(posdcostprice * posdquantity) costvalue,           
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,           
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,          
   (convert(numeric(18,8), sum(posdunitprice ))) -           
   sum(posdcostprice*posdquantity) margin, (convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -           
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin, (convert(numeric(18,8),           
   sum(posdunitprice * poshexchangerate))) - sum(posdcostprice*posdquantity) * poshexchangerate cmargin,
   */
   0.0 costvalue,0.0 dcostvalue,0.0 ccostvalue, 
   0.0 margin,0.0 dmargin,0.0 cmargin,             
   0.00 Exchange,0.00 dExchange,0.00 cExchange,0.00 GReturn,0.00 dGReturn,
   0.00 cGReturn,departmentname, poshdepartmentid  departmentid,          
   pdCheque.PosBankAmount as PdChequeSales,
   (pdCheque.PosBankAmount * poshdepexrate) as  dPdChequeSales,
   (pdCheque.PosBankAmount * poshexchangerate) as cPdChequeSales
   ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount
  from           
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque           
  where           
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND   
   s.shopid = posdshopid and POSHCANCELLED=0 and           
   poshDepartmentid = d.departmentid 
   and isnull(PosPostDate,0)=1 --if PD Cheque Amt is involved  
   and pdCheque.PoshBillID =losposheader.poshbillid
   and pdCheque.PoshShopID =losposheader.poshShopID            
  group by           
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,          
   poshdepexrate, poshexchangerate,losposheader.poshBillid ,pdCheque.PosBankAmount 
 --RefNo-2 Ends --------------------------------------------
 */
 union all          

 --RefNo-5 start commented below and added

 -- select           
 --  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
 --  convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,           
 --  convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,           
 --  convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,           
 --  convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,           
 --  convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,          
 --  convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,          
 --  (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -           
	--	sum(isnull(idcostprice*idquantity,0)))) margin,           
 --  (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -           
	--	sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,           
 --  (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) * ihexchangerate -           
	--	sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin
	--,0.00,0.00,0.00,0.00,0.00,0.00,           
 --  departmentname, ihdepartmentid departmentid           
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
 -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,
 --  convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount
 -- from           
 --  losinvoiceheader  ih          
 --  left outer join losinvoicedetail invd          
 --  on ihInvoiceid=idInvoiceid and ihshopid=idshopid           
 --  left outer join           
 --  (select          
 --   ioShopID,ioInvoiceID,sum(ioAmount) ioAmount          
 --  from          
 --   losInvoiceOC           
 --  group by          
 --  ioShopID,ioInvoiceID) ocd           
 --  on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,           
 --  ashops s, adepartmentmaster d           
 -- where           
 --  IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and           
 --  ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'          
 -- group by           
 --  shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,           
 --  ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount          
 
 
   --credit invoice
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) creditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihexchangerate) ccreditsales,             

   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -      
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,  
                    
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) -             
		 sum(isnull(idcostprice*idquantity,0)))) margin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,      
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihexchangerate -             
		   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,
		0.00,0.00,0.00,0.00,0.00,0.00,    
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from          
    
     losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid
   
   union all
   
   --Other Charges (Credit Invoice)
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) creditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate) ccreditsales,             
   0 costvalue,0 dcostvalue,0 ccostvalue,                  
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))Margin,            
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))* ihdepexrate  dmargin,             
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))) * ihexchangerate cmargin,  

   0.00,0.00,0.00,0.00,0.00,0.00,  
   departmentname, ihdepartmentid departmentid,
   0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales 
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihexchangerate)cGSTAmount  
  from          
     losinvoiceheader  ih                  
   left outer join losInvoiceOC ocd  on ihshopid= ocd.ioShopid 
			and ihinvoiceid=ocd.ioInvoiceID         
	,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by  
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid,ocd.ioShopID,ocd.ioInvoiceID
--RefNo-5 ends
 
 union all          
          
  select           
   shopname, ihShopID, ihinvoicedate,          
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,           
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,           
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,           
   0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,           
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))) costvalue,           
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,          
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,          
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -           
		sum(isnull(idcostprice*idquantity,0)))) margin,           
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) * ihdepexrate -           
		sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,           
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -           
		sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin
	,0.00,0.00,0.00,0.00,0.00,0.00,           
   departmentname, ihdepartmentid departmentid           
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,
    convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount
  from           
   losinvoiceheader  ih          
   left outer join losinvoicedetail invd          
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid           
   left outer join           
   (select          
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount          
   from          
    losInvoiceOC           
   group by          
   ioShopID,ioInvoiceID) ocd           
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,           
   ashops s, adepartmentmaster d           
  where           
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and           
   ihcashinvoice=1 and ihdepartmentid = d.departmentid and ihtype ='i'          
  group by           
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,           
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount          
          
 union all          
   
   select           
   shopname, sehshopid, sehexchangedate, convert(numeric(18,8),           
   sum(cashsales )) cashsales, convert(numeric(18,8),           
   sum(dcashsales)) dcashsales,convert(numeric(18,8),           
   sum(ccashsales)) ccashsales, 0.0 creditsales,           
   0.0 dcreditsales , 0.0 ccreditsales , sum(costvalue) costvalue,          
   sum(dcostvalue) dcostvalue,sum(ccostvalue) ccostvalue,          
   sum(margin) margin, sum(dmargin) dmargin, sum(cmargin)cmargin,
   0.00,0.00,0.00,0.00,0.00,0.00, departmentname, departmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),sum(GSTAmount)) GSTAmount  
  ,convert(numeric(18,8),sum(dGSTAmount)) dGSTAmount  
  ,convert(numeric(18,8),sum(cGSTAmount)) cGSTAmount  
  from           
      vwPosExchangeDetailsWithMarginWithOutGST      
  group by           
   shopname, sehshopid, departmentname, departmentid, sehexchangedate ,          
   departmentname,sehExchangeID   
  having sum(cashsales )>0       
 
union all  
        
   select           
   shopname, sehshopid, sehexchangedate,0.00,0.00,0.00, 0.0 creditsales,           
   0.0 dcreditsales , 0.0 ccreditsales , sum(costvalue) costvalue,          
   sum(dcostvalue) dcostvalue,sum(ccostvalue) ccostvalue,          
   sum(margin) margin, sum(dmargin) dmargin, sum(cmargin)cmargin,
   convert(numeric(18,8),           
   sum(cashsales )) Exchange, convert(numeric(18,8),           
   sum(dcashsales)) dExchange,convert(numeric(18,8),           
   sum(ccashsales)) cExchange,0.00,0.00,0.00, departmentname, departmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),sum(GSTAmount)) GSTAmount 
  ,convert(numeric(18,8),sum(dGSTAmount)) dGSTAmount  
  ,convert(numeric(18,8),sum(cGSTAmount)) cGSTAmount  

  from           
   vwPosExchangeDetailsWithMarginWithOutGST         
  group by           
   shopname, sehshopid, departmentname, departmentid, sehexchangedate ,          
   departmentname,sehExchangeID   
  having sum(cashsales )<0  

 union all    
 
-- RefNo-3 starts
-- special Invoice (cash)  
select   
shopname,                               
 ihshopid, ihinvoicedate,            
 convert(numeric(18, 8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,
 convert(numeric(18, 8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,
 convert(numeric(18, 8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales, 
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                
 sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
 sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0) )))- sum(idcostprice*reqqty) margin,           
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,      
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0) ))- sum(idcostprice*reqqty))* ihexchangerate cmargin,
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                              
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0 
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                       
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                             
union all                                

-------- special invoice - return before despatch                    
select shopname,                               
  ihshopid, ihinvoicedate,            
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales, 
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                
 -sum(idcostprice * reqqty) costvalue ,
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,           

-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty)) margin,           
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,           
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
 
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1 
 and ihNoofOCDetails<>0    
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                         
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                                    
union all                                

 --Special invoice return  - after desp                              
select shopname,                               
 ihshopid, ihinvoicedate,            
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,     
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                
sum(idcostprice * reqqty) costvalue,
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  , 
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) margin,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where  
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1                               
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID  
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
 
-- special Invoice (credit)
union all
select   
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,           
  0.0 ccashsales, 
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
 sum(idcostprice * reqqty) costvalue,
 sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
 sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
--(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty) margin,           
--(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
--(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))))-sum(idcostprice*reqqty) margin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      

0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
 
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where                                 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                              
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                
 and IhTransFinished = 1 And ihcAshinvoice <>1 and ihNoofOCDetails=0 
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                       
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid,
  ihdepartmentid,     
 ihdepexrate, ihexchangerate
                             
union all                                

-- special invoice - return before despatch                    
select   
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,           
  0.0 ccashsales, 
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,  
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
-- sum(idcostprice * reqqty) costvalue,
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,           
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,0.00,0.00,0.00,0.00,0.00,0.00,
 -sum(idcostprice * reqqty) costvalue ,
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,           

-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty)) margin,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice <>1 and ihTransFinished = 1 
 and ihNoofOCDetails<>0    
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                         
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                                    
union all                                
                             
-- Special invoice return  - after desp                              
select   
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,           
  0.0 ccashsales, 
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)dcreditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)ccreditsales,       
 -- sum(idcostprice * reqqty) costvalue,
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,           
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,0.00,0.00,0.00,0.00,0.00,0.00,
sum(idcostprice * reqqty) costvalue,
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  , 
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,           
 ---(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) margin,           
 ---(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,           
 ---(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where          
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice <>1                               
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID  
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid,
  ihdepartmentid,     
 ihdepexrate, ihexchangerate

 
       
 ------ --gave idratetype condition for special invoice return          
 ------ --special invoice return - cash          
 ------ select           
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),           
 ------  sum(idunitprice )) cashsales, convert(numeric(18,8),           
 ------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,8),           
 ------  sum(idunitprice * ihexchangerate)) ccashsales,          
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,           
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
 ------  (convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,           
 ------  (convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
 ------  (convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,0.00,0.00,0.00,0.00,0.00,0.00,
 ------  departmentname, ihdepartmentid departmentid         
 ------ ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 ------ from           
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d           
 ------ where           
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and           
 ------  ihdepartmentid =d.departmentid and idratetype=0 and ihproforma=0 and           
 ------  ihshopid = shopid and ihcashinvoice=1 and ihTransfinished = 1          
 ------ group by           
 ------  shopname, ihshopid, departmentname, ihdepartmentid,           
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid          
 ------ union all         
  
 ------ --special invoice return - credit          
 ------ select           
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,           
 ------  0.0 ccashsales, convert(numeric(18,8), sum(idunitprice )) creditsales,           
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate)) dcreditsales,           
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate)) ccreditsales,           
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,          
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,          
 ------  convert(numeric(18,8), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,        
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,           
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate) - sum(idcostprice*reqqty) * ihexchangerate) cmargin,           
 ------  0.00,0.00,0.00,0.00,0.00,0.00,departmentname, ihDepartmentId departmentid           
 ------ ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 ------ from           
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,           
 ------  adepartmentmaster d           
 ------ where           
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and           
 ------  idratetype=0 and ihproforma=0 and ihshopid = shopid and           
 ------  ihcashinvoice=0 and ihDepartmentId = d.departmentid          
 ------  and ihTransfinished = 1          
 ------ group by           
 ------  shopname, ihshopid, ihdepartmentid, departmentname, ihinvoicedate ,           
 ------  ihexchangerate, ihdepexrate,ihInvoiceid          
                   
 ------union all          
 ------ --gave idratetype condition for special invoice return          
 ------ --special invoice return - cash          
 ------ select           
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),           
 ------  -(sum(idunitprice ))) cashsales, convert(numeric(18,8),           
 ------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,8),           
 ------  -(sum(idunitprice * ihexchangerate))) ccashsales,           
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(idcostprice * abs(reqqty)) costvalue,           
 ------  sum(idcostprice * abs(reqqty)) * ihdepexrate dcostvalue, sum(idcostprice * abs(reqqty)) *           
 ------  ihexchangerate ccostvalue,  -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,           
 ------  0.00,0.00,0.00,0.00,0.00,0.00,departmentname, ihdepartmentid departmentid           
 ------ ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 ------ from           
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d           
 ------ where           
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0            
 ------  and ihproforma=0 and ihshopid = shopid and ihTransfinished = 1           
 ------  and ihcashinvoice=1 AND IDratetype=1 and           
 ------  ihdepartmentid = d.departmentid           
 ------ group by           
 ------  shopname, ihdepartmentid, departmentname, ihshopid,           
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid     
          
 ------union all          
 ------ --special invoice return - credit          
 ------ select           
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
 ------  -(convert(numeric(18,8), sum(idunitprice ))) creditsales,           
 ------  -(convert(numeric(18,8), sum(idunitprice * ihdepexrate))) dcreditsales,           
 ------  -(convert(numeric(18,8), sum(idunitprice * ihexchangerate))) ccreditsales,           
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,           
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
 ------  -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8),           
 ------  sum(idunitprice ))) -  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,           
 ------  0.00,0.00,0.00,0.00,0.00,0.00,departmentname, ihdepartmentid departmentid           
 ------ ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 ------ from           
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,           
 ------  adepartmentmaster d           
 ------ where           
 ------  ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND           
 ------  IHCANCELLED = 0 and ihproforma = 0 and ihshopid = shopid and           
 ------  ihcashinvoice = 0 and idratetype = 1 and ihtransfinished = 1 and           
 ------  ihdepartmentid = d.departmentid           
 ------ group by           
 ------  shopname, ihshopid, ihdepartmentid, departmentname,          
 ------  ihinvoicedate , ihexchangerate, ihdepexrate,ihInvoiceid          

-- RefNo-3 ends
           
 union all          
           
  select           
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,0.00,0.00,0.00,  
   -sum(grncostprice*grndquantity) costvalue, - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,           
   -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,           
   
   - --(convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) - sum(grncostprice*grndquantity)) margin,
   - --(convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) - sum(grncostprice*grndquantity))* grnhdepexRate dmargin,
   - --(convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) - sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,           
   
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))))-  
sum(grncostprice*grndquantity)) margin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -                   
       sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -  
        sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,                   
   0.00,0.00,0.00,
   -convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) GReturn,           
   -convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0))) * grnhdepexRate) dGReturn,           
   -convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0))) * grnhExchangeRate) cGReturn,
   departmentname, grnhdepartmentid departmentid          
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
  ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,
   -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount
  from           
   losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d           
  where           
   GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0           
   and grnhshopid = shopid and grnhdepartmentid = d.departmentid           
  group by           
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,           
   grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID          

  --hari added to include the service booking invoice parts replaced items          
 UNION ALL          
 
  --service invoice (cash) 
  select           
   shopname, repinvdshopid, serinvhdate, 
   --convert(numeric(18,8),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))) cashsales,
   --convert(numeric(18,8),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))* seinvhdepexrate) dcashsales,          
   --convert(numeric(18,8),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate) ccashsales,          
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales,    
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales,                  

   0.0 creditsales, 0.0 dcreditsales , 0.0 ccreditsales ,
   sum(repinvdcostprice * repinvdqty) costvalue,           
   sum(repinvdcostprice * repinvdqty) * seinvhdepexrate  dcostvalue,           
   sum(repinvdcostprice * repinvdqty) *serinvhcmpexrate ccostvalue,           
   
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),           
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,          
   
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
   --   -sum(repinvdcostprice * repinvdqty)margin,             
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
   --   -sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate dmargin,  
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
   --   -sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate cmargin,            

   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty)margin,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))  
      -sum(repinvdcostprice * repinvdqty)) *  seinvhdepexrate dmargin,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))  
 -sum(repinvdcostprice * repinvdqty)) *  serinvhcmpexrate cmargin,          

   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, serinvhDepartmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2

 --RefNo-4  start commneted, since this gst amount is taken care in below
  --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount
  --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,
  --convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount
    ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
--RefNo-4 ends
  from           
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d           
  where           
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0           
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1          
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0        
  group by           
   shopname, repinvdshopid, serinvhDepartmentid,           
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid           
          
 union all          
 
 --service Details (cash)      
  select           
   shopname, serinvhshopid, serinvhdate,
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0))cashsales ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate)dcashsales ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate)ccashsales ,           
   --convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))cashsales ,             
   --convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate)dcashsales ,             
   --convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate)ccashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales ,  --RefNo-13 changed bracket         
   
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,               
   0 costvalue, 0 dcostvalue, 0 ccostvalue,           
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)),           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) *  serinvhcmpexrate) ,           
   --convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   --convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) ,             
   --convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate,             

   
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, serinvhDepartmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount
  ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,
   convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount
  from           
--RefNo-4 start commented below
  -- losserviceinvheader, ashops s, adepartmentmaster d           
  --where           
  -- serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1          
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid     
losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid   and Patindex('%y%',repinvdtype)>0 
 where                   
	serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1  
    and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-4 ends 
 
 union all

  --service invoice (credit)        
  select           
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccreditsales ,             

   sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*           
   seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,           
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * seinvhdepexrate,  
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))-sum(repinvdcostprice * repinvdqty)) * seinvhdepexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))-sum(repinvdcostprice * repinvdqty)) * serinvhcmpexrate,  
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, serinvhDepartmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  --RefNo-4  start commneted, since this gst amount is taken care in below
  --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount
  --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,
  -- convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount
    ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
    --RefNo-4  ends
  from           
   losinvoicedpartsreplacedetails, losserviceinvheader,           
   ashops s, adepartmentmaster d 
  where 
	serinvhid = repinvinvoiceid and           
    serinvhshopid = repinvdshopid AND serinvhcancelled=0           
    and repinvdshopid = shopid and serinvhcashacc is null           
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid            
   and Patindex('%y%',repinvdtype)>0        
  group by           
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,          
   serinvhcmpexrate ,serinvhid           
  
  union all          
  
--  --service Details          
  select           
   shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
   --convert(numeric(18,8),serinvhserviceamt- (isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) creditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))creditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))*seinvhdepexrate dcreditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))*serinvhcmpexrate ccreditsales ,             
   0 costvalue, 0 dcostvalue, 0 ccostvalue,           
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))*seinvhdepexrate) ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))*serinvhcmpexrate) ,           
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*seinvhdepexrate) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*serinvhcmpexrate) ,             
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, serinvhDepartmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount
  ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,
   convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount
from  
   --RefNo-4 start commented below         
  -- losserviceinvheader, ashops s, adepartmentmaster d           
  --where           
  -- serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0          
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid      
  losserviceinvheader
	  inner join  ashops s on serinvhshopid = shopid 
	  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
	  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
	  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
	  and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0 
 where                   
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-4 ends

  union all          
         
  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002          
  --credit          
 
  select           
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,           
   0.0 ccashsales,          
   convert(numeric(18,8), sum(redunitprice)) creditsales,           
   convert(numeric(18,8), sum(redunitprice * rehdepexrate))  dcreditsales, 
   convert(numeric(18,8), sum(redunitprice * rehexchangerate)) ccreditsales, sum(redcostprice * redquantity) costvalue,           
   sum(redcostprice * redquantity) * rehdepexrate dcostvalue, sum(redcostprice * redquantity) *           
   rehexchangerate ccostvalue,  (convert(numeric(18,8), sum(redunitprice ))) -           
   sum(redcostprice * redquantity) margin, (convert(numeric(18,8), sum(redunitprice * rehdepexrate))) -           
   sum(redcostprice * redquantity) * rehdepexrate dmargin,(convert(numeric(18,8),           
   sum(redunitprice * rehexchangerate))) - sum(redcostprice * redquantity) * rehexchangerate cmargin,           
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, rehdepartmentid          
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,0.0 GSTAmount ,0.0 dGSTAmount,0.0 cGSTAmount
  from           
   losExportDetail, losExportHeader, ashops s, adepartmentmaster d           
  where           
   rehExportID = redExportID and rehshopid = redshopid AND           
   reHCANCELLED=0 and rehtype ='i' and          
   rehproforma=0 and rehshopid = shopid and rehcashinvoice=0 and           
   rehdepartmentid = d.departmentid           
  group by           
   shopname, rehshopid, departmentname, rehdepartmentid, rehExportDate,           
   rehdepexrate, rehexchangerate,rehExportID           
          
 union all          
 -- added From Vwcashsales -Margin Not calculating          
           
 select           
  s.shopname, vws.sishopid, vws.siinvoicedate,           
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,           
  --convert(numeric(18,8),sum(vws.siamount * aidepexrate)) as  dcashsales,           
  --convert(numeric(18,8),sum(vws.siamount * aiexchangerate)) as ccashsales,  
  convert(numeric(18,8),sum(vws.sidamount)) as  dcashsales,  
  convert(numeric(18,8),sum(vws.sicamount)) as ccashsales,   
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,           
   0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,          
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,           
  --convert(numeric(18,8),sum(vws.siamount * aidepexrate)) as  dcashsales,           
  --convert(numeric(18,8),sum(vws.siamount * aiexchangerate)) as ccashsales, 
  convert(numeric(18,8),sum(vws.sidamount))as  dmargin,  
  convert(numeric(18,8),sum(vws.sicamount))as cmargin,  
  0.00,0.00,0.00,0.00,0.00,0.00,d.departmentname,lah.aidepartmentid  departmentid           
 ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 , sum(vws.GSTAmount)as GSTAmount
 , sum(vws.dGSTAmount)as dGSTAmount
 , sum(vws.cGSTAmount)as cGSTAmount
 from           
  vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d ,ashops s          
 where           
  aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and           
  aishopid = sishopid and lah.aicashinvoice=1 and           
  lah.aidepartmentid =d.departmentid and s.departmentid = d.departmentid          
  and aiShopId = s.ShopId          
 group by           
  s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid, vws.siinvoicedate          
          
 union all          
          
    select s.shopname, vws.sishopid, vws.siinvoicedate,           
    0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,           
    convert(numeric(18,8),sum(vws.siamount)) as  creditsales,           
    --convert(numeric(18,8),sum(vws.siamount * aidepexrate)) as   dcreditsales,           
    --convert(numeric(18,8),sum(vws.siamount * aiexchangerate)) as ccreditsales,  
    convert(numeric(18,8),sum(vws.sidamount)) as  dcreditsales,  
	convert(numeric(18,8),sum(vws.sicamount)) as ccreditsales,   
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,          
    convert(numeric(18,8),sum(vws.siamount)) as  margin,           
    --convert(numeric(18,8),sum(vws.siamount * aidepexrate)) as   dmargin,           
    --convert(numeric(18,8),sum(vws.siamount * aiexchangerate)) as cmargin,          
    convert(numeric(18,8),sum(vws.sidamount))as dmargin,  
    convert(numeric(18,8),sum(vws.sicamount))as cmargin,  
    0.00,0.00,0.00,0.00,0.00,0.00,d.departmentname,lah.aidepartmentid  departmentid           
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
    , sum(vws.GSTAmount)as GSTAmount
     , sum(vws.dGSTAmount)as dGSTAmount
	 , sum(vws.cGSTAmount)as cGSTAmount
    from vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d,ashops s          
    where aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and           
    aishopid = sishopid and lah.aicashinvoice=0 and lah.aidepartmentid =d.departmentid          
    and s.departmentid = d.departmentid and s.ShopId = aiShopId group by               
    s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid,vws.siinvoicedate,aiinvoiceid           
           
    UniOn All -- added from vwCashSales         
    --Shop debit credit notes and handling debit notes which are debit to the        
    -- customer and hence act as invoices to be settled              
    Select  s.shopname,losdcnshopid,losdcndate,      
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,          
    COnvert(numeric(18,8),Sum(losDCNAmount))  creditsales,             
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dcreditsales,       
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  ccreditsales,       
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                   
    COnvert(numeric(18,8),Sum(losDCNAmount))  margin,             
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dmargin,       
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  cmargin,      
    0.00,0.00,0.00,0.00,0.00,0.00,d.departmentname,losdcndepartmentid           
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
     ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount
    From Ashops s,  losdebitcreditnote, adepartmentmaster d       
    Where  s.shopid = losdcnshopid And s.accountable Is Not Null           
    And d.DepartmentID = losdcndepartmentid And losdcncancelled =0            
    And losdcndebit =1  Group By s.shopname,d.departmentname,losdcnshopid,          
    losdcndate, losdepexrate, losexchangerate,losdcndepartmentid      
      
    --hq serivce invoice dOne for shop            
    Union all      
       
    Select  null, 0,ai.invoicedate,      
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,          
	COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,               
	COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,         
	COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)ccreditsales,         
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                   
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,             
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,       
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)) * exchangerate)cmargin,      

    0.00,0.00,0.00,0.00,0.00,0.00,d.departmentname,ai.departmentid   
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
    ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount 
    ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,
     convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount

    From accountsinvoiceheader ai, serviceinvoicedetails ser ,adepartmentmaster d       
    Where ai.invoiceid = ser.invoiceid And ai.companyid =             
    ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0     
    and ai.departmentid = d.departmentid and ai.companyid = d.companyid       
    Group By  ai.invoicedate,depexrate,exchangerate,      
    d.departmentname,ai.departmentid          
          
 ) cashcreditcollection          
group by           
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,           
 cashcreditcollection.departmentname, cashcreditcollection.departmentid,           
 cashcreditcollection.poshbilldate          
          
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Daily Sales and Returns GST Separately by bijesh on 25.09.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

use [adminv2]
go
IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwPosExchangeDetailsWithMarginWithOutGST')
   DROP view dbo.vwPosExchangeDetailsWithMarginWithOutGST
GO

--RefNo        : Newly created view (copy of vwPosExchangeDetailsWithMargin)
--Modified by  : Bijesh.B
--Date         : 13/03/2012
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Need to show GST separately
----------------------------------------------------------------------------------------------   
--Modified by  : Bijesh.B
--Date         : 24/09/2012
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Corrected margin values for goods exchange
----------------------------------------------------------------------------------------------   

create View vwPosExchangeDetailsWithMarginWithOutGST   as

select           
   sehExchangeID,shopname, sehshopid, sehexchangedate, 
   convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0))) cashsales,
   convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehdepexrate) dcashsales,
   convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehexchangerate) ccashsales,
   0.0 creditsales,0.0 dcreditsales , 0.0 ccreditsales , sum(sedcostprice * sedquantity) costvalue,          
   sum(sedcostprice * sedquantity) * sehdepexrate dcostvalue,           
  sum(sedcostprice * sedquantity) * sehexchangerate ccostvalue,          
   
   convert(numeric(18,8), sum(sedunitprice-isnull(sedItemTaxAmount,0))) - sum(sedcostprice * sedquantity) margin, 
   convert(numeric(18,8), sum(sedunitprice-isnull(sedItemTaxAmount,0)* sehdepexrate)) -           
					sum(sedcostprice * sedquantity) * sehdepexrate dmargin, 
   convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0)* sehexchangerate)) - 
					sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,
	departmentname, sehdepartmentid departmentid
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount
     ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
    convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount
  from           
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d           
  where   
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and           
   sedbillorexchange = 'E' and sehshopid = shopid and sehdepartmentid = d.departmentid           
  group by           
   shopname, sehshopid, departmentname, sehdepartmentid, sehexchangedate ,          
   departmentname,sehdepexrate, sehexchangerate,sehExchangeID  

 union all          
          
   select           
   sedExchangeID,shopname, sehshopid, sehexchangedate,
   convert(numeric(18,8),-sum(sedunitprice-isnull(sedItemTaxAmount,0))) cashsales,
   convert(numeric(18,8),-sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehdepexrate) dcashsales,
   convert(numeric(18,8),-sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehexchangerate) ccashsales,          
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,- sum(sedcostprice * sedExchangeQty) costvalue,          
   -sum(sedcostprice * sedExchangeQty) * sehdepexrate dcostvalue, -sum(sedcostprice * sedExchangeQty)           
   * sehexchangerate ccostvalue, 
   -(convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0)))- sum(sedcostprice * sedExchangeQty)) margin,
   -(convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0)))-sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,
   -(convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0)))- sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,           
   departmentname, sehdepartmentid departmentid
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount    
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
    convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount
  from           
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d           
  where    
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and           
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid           
   and sehdepartmentid = d.departmentid           
  group by           
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,          
   sehdepexrate,sedExchangeid  




GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Wings Update on 25/09/2012 from AADYAKUMAR.D.V
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
---------------------------------------------
--Created By:AADYAKUMAR.D.V
--Created On:25/09/2012
--Created For:Showing report for cash drawer openings in F&B
--This report shows the cash drawer opening with shot cut ket F12
----------------------------------------------------
GO

use [adminv2]
go
IF EXISTS(SELECT *  FROM sys.views WHERE name ='VwCashDrawer')
   DROP view VwCashDrawer
GO

Create view VwCashDrawer
as
select CD.UserId,U.UserName,CD.OpenedTime,CD.OpenType,CD.ShopId
from LosCashDrawerOpen CD
inner join LOUsers U on CD.UserId=U.UserID
Where OpenType='Open'

go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Update Description [Daily Sales and Returns GST Separately] – Defect Sheet on 26.09.2012 from Bijesh
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

use [adminv2]
go
IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwPosExchangeDetailsWithMarginWithOutGST')
   DROP view dbo.vwPosExchangeDetailsWithMarginWithOutGST
GO

--RefNo        : Newly created view (copy of vwPosExchangeDetailsWithMargin)
--Modified by  : Bijesh.B
--Date         : 13/03/2012
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Need to show GST separately
----------------------------------------------------------------------------------------------   
--Modified by  : Bijesh.B
--Date         : 24/09/2012
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Corrected margin values for goods exchange
----------------------------------------------------------------------------------------------   
--Modified by  : BIJESH.B   
--RefNo        : RefNo-1
--Date         : 26/09/2012  
--Comments     : If new items was added in Goods Exchange, it should 
--				 cosidered as Cash Sales (BugSheet)
----------------------------------------------------------------------------------------------       

create View vwPosExchangeDetailsWithMarginWithOutGST   as

select           
   sehExchangeID,shopname, sehshopid, sehexchangedate, 
   convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0))) cashsales,
   convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehdepexrate) dcashsales,
   convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehexchangerate) ccashsales,
   0.0 creditsales,0.0 dcreditsales , 0.0 ccreditsales , sum(sedcostprice * sedquantity) costvalue,          
   sum(sedcostprice * sedquantity) * sehdepexrate dcostvalue,           
  sum(sedcostprice * sedquantity) * sehexchangerate ccostvalue,          
   
   convert(numeric(18,8), sum(sedunitprice-isnull(sedItemTaxAmount,0))) - sum(sedcostprice * sedquantity) margin, 
   convert(numeric(18,8), sum(sedunitprice-isnull(sedItemTaxAmount,0)* sehdepexrate)) -           
					sum(sedcostprice * sedquantity) * sehdepexrate dmargin, 
   convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0)* sehexchangerate)) - 
					sum(sedcostprice * sedquantity)* sehexchangerate  cmargin,
	departmentname, sehdepartmentid departmentid
   ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount
     ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
    convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount,
    'E' BillOrExchange --RefNo-1 added
  from           
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d           
  where   
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and           
   sedbillorexchange = 'E' and sehshopid = shopid and sehdepartmentid = d.departmentid           
  group by           
   shopname, sehshopid, departmentname, sehdepartmentid, sehexchangedate ,          
   departmentname,sehdepexrate, sehexchangerate,sehExchangeID  

 union all          
          
   select           
   sedExchangeID,shopname, sehshopid, sehexchangedate,
   convert(numeric(18,8),-sum(sedunitprice-isnull(sedItemTaxAmount,0))) cashsales,
   convert(numeric(18,8),-sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehdepexrate) dcashsales,
   convert(numeric(18,8),-sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehexchangerate) ccashsales,          
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,- sum(sedcostprice * sedExchangeQty) costvalue,          
   -sum(sedcostprice * sedExchangeQty) * sehdepexrate dcostvalue, -sum(sedcostprice * sedExchangeQty)           
   * sehexchangerate ccostvalue, 
   -(convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0)))- sum(sedcostprice * sedExchangeQty)) margin,
   -(convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0)))-sum(sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,
   -(convert(numeric(18,8),sum(sedunitprice-isnull(sedItemTaxAmount,0)))- sum(sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,           
   departmentname, sehdepartmentid departmentid
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount    
   ,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
    convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount,
    'B' BillOrExchange --RefNo-1 added
  from           
   losposexchangeheader, losposexchangedetail, ashops s, adepartmentmaster d           
  where    
   sedExchangeid=sehExchangeID and sedShopID=sehShopid and SEHCANCELLED=0 and           
   sedbillorexchange ='B' and sedexchangeqty>0 and sehshopid = shopid           
   and sehdepartmentid = d.departmentid           
  group by           
   shopname, sehshopid, sehdepartmentid, departmentname,sehexchangedate, sehexchangerate,          
   sehdepexrate,sedExchangeid  


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Update Description [Daily Sales and Returns GST Separately] – Defect Sheet on 26.09.2012 from Bijesh
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionWithMarginDetWithOutGST')
   DROP view dbo.vwDailySalesCollectionWithMarginDetWithOutGST
GO


---Created ON :13/01/2008
---Comments   :For Daily Sales With Returns Report   
---------------------------------------------------------------------------------------                
--RefNo        : RefNo-2
--Modified by  : Bijesh.B
--Date         : 21/06/2011
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-3
--Modified by  : Bijesh.B
--Date         : 29/07/2011
--Comments     : Bugsheet - Special invoice cash and credit,costvalue and margin is wrong
--             : since, Special invoice return after desp, reqqty is negative,
--				 -1 is multiplied with reqqty
----------------------------------------------------------------------------------------------   
--RefNo        : Newly created view (copy of vwDailySalesCollectionWithMarginDet)
--Modified by  : Bijesh.B
--Date         : 13/03/2012
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Need to show GST separately
----------------------------------------------------------------------------------------------   
--RefNo-4
--Modified by  : Bijesh.B
--Date         : 13/07/2012
--Ticket id    : JDJ-400367 (Sonee)
--comments     : Need to show GST separately - corrected values
----------------------------------------------------------------------------------------------   
--Modified by  : BIJESH.B   
--RefNo        : RefNo-5
--Date         : 01/08/2012  
--Comments     : Corrected Other Charges Service Tax in Credit Invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-6
--Date         : 25/09/2012  
--Comments     : Corrected Dept Margin in case of dollar a/c,
--               GST amt incase of goods return
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-7
--Date         : 26/09/2012  
--Comments     : If new items was added in Goods Exchange, it should 
--				 cosidered as Cash Sales (BugSheet)
----------------------------------------------------------------------------------------------       

create VIEW [dbo].[vwDailySalesCollectionWithMarginDetWithOutGST] AS          
Select           
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,           
 cashcreditcollection.poshbilldate, 
 convert(numeric(18,8),sum(cashsales)) cashsales,          
 convert(numeric(18,8),sum(dcashsales)) dcashsales,           
 convert(numeric(18,8),sum(ccashsales)) ccashsales,          
 convert(numeric(18,8),sum(creditsales)) creditsales,          
 convert(numeric(18,8),sum(dcreditsales)) dcreditsales,           
 convert(numeric(18,8),sum(ccreditsales)) ccreditsales,           
 convert(numeric(18,8),sum(costvalue)) costvalue,          
 convert(numeric(18,8),sum(dcostvalue)) dcostvalue,           
 convert(numeric(18,8),sum(ccostvalue)) ccostvalue,           
 convert(numeric(18,8),sum(margin)) margin,          
 convert(numeric(18,8),sum(dmargin)) dmargin,           
 convert(numeric(18,8),sum(cmargin)) cmargin,
 convert(numeric(18,8),sum(Exchange)) Exchange,          
 convert(numeric(18,8),sum(dExchange)) dExchange,           
 convert(numeric(18,8),sum(cExchange)) cExchange,
 convert(numeric(18,8),sum(GReturn)) GReturn,          
 convert(numeric(18,8),sum(dGReturn)) dGReturn,           
 convert(numeric(18,8),sum(cGReturn)) cGReturn,           
 cashcreditcollection.departmentname, cashcreditcollection.departmentid           
--RefNo-2 start -------------------------
,convert(numeric(18,8),sum(PdChequeSales)) PdChequeSales,
convert(numeric(18,8),sum(dPdChequeSales)) dPdChequeSales,
convert(numeric(18,8),sum(cPdChequeSales)) cPdChequeSales,
--RefNo-2 ends -------------------------
convert(numeric(18,8),sum(GSTAmount))GSTAmount,
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount

from           
 (          
  select           
   shopname, losposheader.poshShopID, poshbilldate, 
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) cashsales, 
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dcashsales,
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) ccashsales,
   0.0 creditsales, 0.0 dcreditsales,0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,           
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,           
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,          
	(convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))))
	 - sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -  
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   
 
   0.00 Exchange,0.00 dExchange,0.00 cExchange,0.00 GReturn,0.00 dGReturn,0.00 cGReturn,
   departmentname, poshdepartmentid  departmentid          
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount
  from           
   losposdetail, losposheader, ashops s, adepartmentmaster d           
  where           
   poshBillid=posdBillid and poshShopid=posdshopid AND           
   s.shopid = posdshopid and POSHCANCELLED=0 and           
   poshDepartmentid = d.departmentid          
   and isnull(PosPostDate,0)=0 --RefNo-2  if No PD Cheque Amt involved                       
  group by           
   shopname, departmentname, poshdepartmentid, poshshopid, poshbilldate, 
   poshdepexrate, poshexchangerate,poshBillid          
     
--RefNo-2 Start --------------------------------------------
 --CASH + PD CHEQUE -> Taking only cash amount
union all
select           
   shopname, losposheader.poshShopID, poshbilldate, 
   --convert(numeric(18,8),sum(posdunitprice )) cashsales, 
   --convert(numeric(18,8),sum(posdunitprice * poshdepexrate)) dcashsales, 
   --convert(numeric(18,8),sum(posdunitprice * poshexchangerate)) ccashsales,

   --convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))-pdCheque.PosBankAmount) cashsales, 
   --convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshdepexrate)-pdCheque.PosBankAmount) dcashsales, 
   --convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0) * poshexchangerate)-pdCheque.PosBankAmount) ccashsales,
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,
   0.0 creditsales, 0.0 dcreditsales,           
   0.0 ccreditsales, sum(posdcostprice * posdquantity) costvalue,           
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,           
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,          

	(convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))))
	 - sum(posdcostprice*posdquantity) margin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                   
        sum(posdcostprice*posdquantity) * poshdepexrate dmargin,  
   (convert(numeric(18,8),sum((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -  
        sum(posdcostprice*posdquantity) * poshexchangerate cmargin,                   

   0.00 Exchange,0.00 dExchange,0.00 cExchange,0.00 GReturn,0.00 dGReturn,0.00 cGReturn,departmentname, poshdepartmentid  departmentid          
   --,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) PdChequeSales, 
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) dPdChequeSales,
   convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) cPdChequeSales
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,
   convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount

  from           
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque           
  where           
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND           
   s.shopid = posdshopid and POSHCANCELLED=0 and           
   poshDepartmentid = d.departmentid 
   and isnull(PosPostDate,0)=1 --if PD Cheque Amt is involved  
   and pdCheque.PoshBillID =losposheader.poshbillid
   and pdCheque.PoshShopID =losposheader.poshShopID            
  group by           
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,          
   poshdepexrate, poshexchangerate,losposheader.poshBillid,pdCheque.PosBankAmount          

/*
union all
 --CASH + PD CHEQUE -> Taking only Cheque amount
 select           
   shopname, losposheader.poshShopID, poshbilldate, 
   0.0 cashsales, 0.0 dcashsales,0.0 ccashsales,
   0.0 creditsales, 0.0 dcreditsales,           
   0.0 ccreditsales,
   /*
   sum(posdcostprice * posdquantity) costvalue,           
   sum(posdcostprice * posdquantity) * poshdepexrate dcostvalue,           
   sum(posdcostprice * posdquantity) * poshexchangerate ccostvalue,          
   (convert(numeric(18,8), sum(posdunitprice ))) -           
   sum(posdcostprice*posdquantity) margin, (convert(numeric(18,8), sum(posdunitprice * poshdepexrate))) -           
   sum(posdcostprice*posdquantity) * poshdepexrate dmargin, (convert(numeric(18,8),           
   sum(posdunitprice * poshexchangerate))) - sum(posdcostprice*posdquantity) * poshexchangerate cmargin,
   */
   0.0 costvalue,0.0 dcostvalue,0.0 ccostvalue, 
   0.0 margin,0.0 dmargin,0.0 cmargin,             
   0.00 Exchange,0.00 dExchange,0.00 cExchange,0.00 GReturn,0.00 dGReturn,
   0.00 cGReturn,departmentname, poshdepartmentid  departmentid,          
   pdCheque.PosBankAmount as PdChequeSales,
   (pdCheque.PosBankAmount * poshdepexrate) as  dPdChequeSales,
   (pdCheque.PosBankAmount * poshexchangerate) as cPdChequeSales
   ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount
  from           
   losposdetail, losposheader, ashops s, adepartmentmaster d,losPosChequeDetails pdCheque           
  where           
   losposheader.poshBillid=posdBillid and losposheader.poshShopid=posdshopid AND   
   s.shopid = posdshopid and POSHCANCELLED=0 and           
   poshDepartmentid = d.departmentid 
   and isnull(PosPostDate,0)=1 --if PD Cheque Amt is involved  
   and pdCheque.PoshBillID =losposheader.poshbillid
   and pdCheque.PoshShopID =losposheader.poshShopID            
  group by           
   shopname, departmentname, poshdepartmentid, losposheader.poshshopid, poshbilldate,          
   poshdepexrate, poshexchangerate,losposheader.poshBillid ,pdCheque.PosBankAmount 
 --RefNo-2 Ends --------------------------------------------
 */
 union all          

 --RefNo-5 start commented below and added

 -- select           
 --  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
 --  convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) creditsales,           
 --  convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,           
 --  convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,           
 --  convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,           
 --  convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,          
 --  convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,          
 --  (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) -           
	--	sum(isnull(idcostprice*idquantity,0)))) margin,           
 --  (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -           
	--	sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,           
 --  (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) * ihexchangerate -           
	--	sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin
	--,0.00,0.00,0.00,0.00,0.00,0.00,           
 --  departmentname, ihdepartmentid departmentid           
 -- ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
 -- ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,
 --  convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount
 -- from           
 --  losinvoiceheader  ih          
 --  left outer join losinvoicedetail invd          
 --  on ihInvoiceid=idInvoiceid and ihshopid=idshopid           
 --  left outer join           
 --  (select          
 --   ioShopID,ioInvoiceID,sum(ioAmount) ioAmount          
 --  from          
 --   losInvoiceOC           
 --  group by          
 --  ioShopID,ioInvoiceID) ocd           
 --  on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,           
 --  ashops s, adepartmentmaster d           
 -- where           
 --  IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and           
 --  ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'          
 -- group by           
 --  shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,           
 --  ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount          
 
 
   --credit invoice
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   --convert(numeric(18,8), sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) creditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dcreditsales,                   
   --convert(numeric(18,8), (sum(isnull(invd.idunitprice,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) ccreditsales,                   
   
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) creditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihexchangerate) ccreditsales,             

   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))) costvalue,                   
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,                  
   convert(numeric(18,8), sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,                  
   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) -      
   --sum(isnull(idcostprice*idquantity,0)))) margin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihdepexrate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihdepexrate)) dmargin,                   
   --(convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -                   
   --sum(isnull(idcostprice*idquantity,0)) * ihexchangerate)) cmargin,  
                    
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) -             
		 sum(isnull(idcostprice*idquantity,0)))) margin,             
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihdepexrate -             
		 (sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,      
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))) * ihexchangerate -             
		   (sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin,
		0.00,0.00,0.00,0.00,0.00,0.00,    
   departmentname, ihdepartmentid departmentid                   
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
  from          
    
     losinvoiceheader  ih                  
   left outer join losinvoicedetail invd                  
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid                   
   ,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by                   
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid
   
   union all
   
   --Other Charges (Credit Invoice)
  select                   
   shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,                   
   convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) creditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) dcreditsales,             
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate) ccreditsales,             
   0 costvalue,0 dcostvalue,0 ccostvalue,                  
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))Margin,            
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))))* ihdepexrate  dmargin,             
   convert(numeric(18,8), (sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))) * ihexchangerate cmargin,  

   0.00,0.00,0.00,0.00,0.00,0.00,  
   departmentname, ihdepartmentid departmentid,
   0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales 
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0)))GSTAmount  
   ,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihdepexrate)dGSTAmount,  
   convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihexchangerate)cGSTAmount  
  from          
     losinvoiceheader  ih                  
   left outer join losInvoiceOC ocd  on ihshopid= ocd.ioShopid 
			and ihinvoiceid=ocd.ioInvoiceID         
	,ashops s, adepartmentmaster d                   
  where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
  group by  
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,                   
   ihdepexrate, ihexchangerate,ihInvoiceid,ocd.ioShopID,ocd.ioInvoiceID
--RefNo-5 ends
 
 union all          
          
  select           
   shopname, ihShopID, ihinvoicedate,          
   convert(numeric(18,8), sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) Cashsales,           
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihdepexrate) dCashsales,           
   convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ isnull(ocd.ioAmount,0)) * ihexchangerate) cCashsales,           
   0.0 Creditsales, 0.0 dCreditsales, 0.0 cCreditsales,           
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))) costvalue,           
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0))* ihdepexrate) dcostvalue,          
   convert(numeric(18,8),sum(isnull(idcostprice * idquantity,0)) * ihexchangerate) ccostvalue,          
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) -           
		sum(isnull(idcostprice*idquantity,0)))) margin,           
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0) ) + isnull(ocd.ioAmount,0)) * ihdepexrate -           
		sum(isnull(idcostprice*idquantity,0))) * ihdepexrate) dmargin,           
   (convert(numeric(18,8), (sum(isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)) + isnull(ocd.ioAmount,0)) * ihexchangerate -           
		sum(isnull(idcostprice*idquantity,0))) * ihexchangerate) cmargin
	,0.00,0.00,0.00,0.00,0.00,0.00,           
   departmentname, ihdepartmentid departmentid           
   ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
   ,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,
    convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount
  from           
   losinvoiceheader  ih          
   left outer join losinvoicedetail invd          
   on ihInvoiceid=idInvoiceid and ihshopid=idshopid           
   left outer join           
   (select          
    ioShopID,ioInvoiceID,sum(ioAmount) ioAmount          
   from          
    losInvoiceOC           
   group by          
   ioShopID,ioInvoiceID) ocd           
   on ihshopid= ocd.ioShopid and ihinvoiceid=ocd.ioInvoiceID ,           
   ashops s, adepartmentmaster d           
  where           
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and           
   ihcashinvoice=1 and ihdepartmentid = d.departmentid and ihtype ='i'          
  group by           
   shopname, ihshopid, departmentname, ihdepartmentid, ihinvoicedate,           
   ihdepexrate, ihexchangerate,ihInvoiceid, ocd.IoAmount          
          
 union all          
   
   select           
   shopname, sehshopid, sehexchangedate, convert(numeric(18,8),           
   sum(cashsales )) cashsales, convert(numeric(18,8),           
   sum(dcashsales)) dcashsales,convert(numeric(18,8),           
   sum(ccashsales)) ccashsales, 0.0 creditsales,           
   0.0 dcreditsales , 0.0 ccreditsales , sum(costvalue) costvalue,          
   sum(dcostvalue) dcostvalue,sum(ccostvalue) ccostvalue,          
   sum(margin) margin, sum(dmargin) dmargin, sum(cmargin)cmargin,
   0.00,0.00,0.00,0.00,0.00,0.00, departmentname, departmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),sum(GSTAmount)) GSTAmount  
  ,convert(numeric(18,8),sum(dGSTAmount)) dGSTAmount  
  ,convert(numeric(18,8),sum(cGSTAmount)) cGSTAmount  
  from           
      vwPosExchangeDetailsWithMarginWithOutGST   
  where BillOrExchange='E' --RefNo-7 added
  group by           
   shopname, sehshopid, departmentname, departmentid, sehexchangedate ,          
   departmentname,sehExchangeID   
  --having sum(cashsales )>0  --RefNo-7 commented
  
 
union all  
        
   select           
   shopname, sehshopid, sehexchangedate,0.00,0.00,0.00, 0.0 creditsales,           
   0.0 dcreditsales , 0.0 ccreditsales , sum(costvalue) costvalue,          
   sum(dcostvalue) dcostvalue,sum(ccostvalue) ccostvalue,          
   sum(margin) margin, sum(dmargin) dmargin, sum(cmargin)cmargin,
   convert(numeric(18,8),           
   sum(cashsales )) Exchange, convert(numeric(18,8),           
   sum(dcashsales)) dExchange,convert(numeric(18,8),           
   sum(ccashsales)) cExchange,0.00,0.00,0.00, departmentname, departmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),sum(GSTAmount)) GSTAmount 
  ,convert(numeric(18,8),sum(dGSTAmount)) dGSTAmount  
  ,convert(numeric(18,8),sum(cGSTAmount)) cGSTAmount  
  from           
   vwPosExchangeDetailsWithMarginWithOutGST         
  where BillOrExchange='B' --RefNo-7 added
  group by           
   shopname, sehshopid, departmentname, departmentid, sehexchangedate ,          
   departmentname,sehExchangeID   
  having sum(cashsales )<0  

 union all    
 
-- RefNo-3 starts
-- special Invoice (cash)  
select   
shopname,                               
 ihshopid, ihinvoicedate,            
 convert(numeric(18, 8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,
 convert(numeric(18, 8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,
 convert(numeric(18, 8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales, 
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                
 sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
 sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0) )))- sum(idcostprice*reqqty) margin,           
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))- sum(idcostprice*reqqty)) * ihdepexrate dmargin,      
(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0) ))- sum(idcostprice*reqqty))* ihexchangerate cmargin,
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
 convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                              
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0 
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                       
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                             
union all                                

-------- special invoice - return before despatch                    
select shopname,                               
  ihshopid, ihinvoicedate,            
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0))) cashsales,
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dcashsales,
 convert(numeric(18, 8),-sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) ccashsales, 
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                
 -sum(idcostprice * reqqty) costvalue ,
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,           

-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty)) margin,           
-- -(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,           
-- -(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
 
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1 
 and ihNoofOCDetails<>0    
  and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                         
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                                    
union all                                

 --Special invoice return  - after desp                              
select shopname,                               
 ihshopid, ihinvoicedate,            
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) cashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcashsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccashsales,     
 0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,                                
sum(idcostprice * reqqty) costvalue,
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  , 
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) margin,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where  
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1                               
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID  
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
 
-- special Invoice (credit)
union all
select   
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,           
  0.0 ccashsales, 
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,      
 convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
 sum(idcostprice * reqqty) costvalue,
 sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
 sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
--(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*reqqty) margin,           
--(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
--(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))))-sum(idcostprice*reqqty) margin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty)) * ihdepexrate dmargin,                 
(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))-sum(idcostprice*reqqty))* ihexchangerate cmargin,      

0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
 
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where                                 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                              
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                
 and IhTransFinished = 1 And ihcAshinvoice <>1 and ihNoofOCDetails=0 
 and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                       
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid,
  ihdepartmentid,     
 ihdepexrate, ihexchangerate
                             
union all                                

-- special invoice - return before despatch                    
select   
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,           
  0.0 ccashsales, 
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) dcreditsales,  
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) ccreditsales,    
-- sum(idcostprice * reqqty) costvalue,
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,           
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,0.00,0.00,0.00,0.00,0.00,0.00,
 -sum(idcostprice * reqqty) costvalue ,
 -sum(idcostprice * reqqty) * ihdepexrate dcostvalue ,
 -sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,           

-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty)) margin,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty)) * ihdepexrate dmargin ,           
-- -(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*reqqty))* ihexchangerate cmargin,
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0))))- sum(idcostprice*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice <>1 and ihTransFinished = 1 
 and ihNoofOCDetails<>0    
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID                         
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                                    
union all                                
                             
-- Special invoice return  - after desp                              
select   
shopname, ihshopid, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,           
  0.0 ccashsales, 
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) creditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)dcreditsales,      
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)ccreditsales,       
 -- sum(idcostprice * reqqty) costvalue,
-- sum(idcostprice * reqqty) * ihdepexrate dcostvalue,
-- sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
--(convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,           
--(convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
--(convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,0.00,0.00,0.00,0.00,0.00,0.00,
sum(idcostprice * reqqty) costvalue,
sum(idcostprice * reqqty) * ihdepexrate dcostvalue  , 
sum(idcostprice * reqqty) * ihexchangerate ccostvalue ,           
 ---(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) margin,           
 ---(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,           
 ---(convert(numeric(18,8), sum(idunitprice-isnull(idItemTaxAmount,0))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) margin,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty)) * ihdepexrate dmargin ,                 
-(convert(numeric(18,8), sum((idunitprice-isnull(idItemTaxAmount,0)))) - sum(idcostprice*-1*reqqty))* ihexchangerate cmargin,      
0.00,0.00,0.00,0.00,0.00,0.00,
departmentname, ihdepartmentid departmentid         
,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount 
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail,losspecialinvoiceheader,ashops s,adepartmentmaster d                                 
where          
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice <>1                               
and ihshopid = ShopID  and   d.DepartmentID=IhDepartmentID  
Group By  
 shopname,departmentname,ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid,
  ihdepartmentid,     
 ihdepexrate, ihexchangerate

 
       
 ------ --gave idratetype condition for special invoice return          
 ------ --special invoice return - cash          
 ------ select           
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),           
 ------  sum(idunitprice )) cashsales, convert(numeric(18,8),           
 ------  sum(idunitprice * ihdepexrate)) dcashsales,convert(numeric(18,8),           
 ------  sum(idunitprice * ihexchangerate)) ccashsales,          
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,           
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue, sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
 ------  (convert(numeric(18,8), sum(idunitprice ))) - sum(idcostprice*reqqty) margin,           
 ------  (convert(numeric(18,8), sum(idunitprice)) - sum(idcostprice*reqqty)) * ihdepexrate dmargin,           
 ------  (convert(numeric(18,8), sum(idunitprice )) - sum(idcostprice*reqqty))* ihexchangerate cmargin,0.00,0.00,0.00,0.00,0.00,0.00,
 ------  departmentname, ihdepartmentid departmentid         
 ------ ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 ------ from           
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d           
 ------ where           
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and           
 ------  ihdepartmentid =d.departmentid and idratetype=0 and ihproforma=0 and           
 ------  ihshopid = shopid and ihcashinvoice=1 and ihTransfinished = 1          
 ------ group by           
 ------  shopname, ihshopid, departmentname, ihdepartmentid,           
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid          
 ------ union all         
  
 ------ --special invoice return - credit          
 ------ select           
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales,           
 ------  0.0 ccashsales, convert(numeric(18,8), sum(idunitprice )) creditsales,           
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate)) dcreditsales,           
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate)) ccreditsales,           
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,          
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,          
 ------  convert(numeric(18,8), sum(idunitprice ) - sum(idcostprice*reqqty)) margin,        
 ------  convert(numeric(18,8), sum(idunitprice * ihdepexrate) - sum(idcostprice*reqqty) * ihdepexrate) dmargin,           
 ------  convert(numeric(18,8), sum(idunitprice * ihexchangerate) - sum(idcostprice*reqqty) * ihexchangerate) cmargin,           
 ------  0.00,0.00,0.00,0.00,0.00,0.00,departmentname, ihDepartmentId departmentid           
 ------ ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 ------ from           
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,           
 ------  adepartmentmaster d           
 ------ where           
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0 and           
 ------  idratetype=0 and ihproforma=0 and ihshopid = shopid and           
 ------  ihcashinvoice=0 and ihDepartmentId = d.departmentid          
 ------  and ihTransfinished = 1          
 ------ group by           
 ------  shopname, ihshopid, ihdepartmentid, departmentname, ihinvoicedate ,           
 ------  ihexchangerate, ihdepexrate,ihInvoiceid          
                   
 ------union all          
 ------ --gave idratetype condition for special invoice return          
 ------ --special invoice return - cash          
 ------ select           
 ------  shopname, ihShopID, ihinvoicedate, convert(numeric(18,8),           
 ------  -(sum(idunitprice ))) cashsales, convert(numeric(18,8),           
 ------  -(sum(idunitprice * ihdepexrate))) dcashsales, convert(numeric(18,8),           
 ------  -(sum(idunitprice * ihexchangerate))) ccashsales,           
 ------  0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales, sum(idcostprice * abs(reqqty)) costvalue,           
 ------  sum(idcostprice * abs(reqqty)) * ihdepexrate dcostvalue, sum(idcostprice * abs(reqqty)) *           
 ------  ihexchangerate ccostvalue,  -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,           
 ------  0.00,0.00,0.00,0.00,0.00,0.00,departmentname, ihdepartmentid departmentid           
 ------ ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 ------ from           
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s, adepartmentmaster d           
 ------ where           
 ------  ihInvoiceid=idInvoiceid  and ihshopid=idshopid AND IHCANCELLED=0            
 ------  and ihproforma=0 and ihshopid = shopid and ihTransfinished = 1           
 ------  and ihcashinvoice=1 AND IDratetype=1 and           
 ------  ihdepartmentid = d.departmentid           
 ------ group by           
 ------  shopname, ihdepartmentid, departmentname, ihshopid,           
 ------  ihinvoicedate, ihexchangerate, ihdepexrate,ihInvoiceid     
          
 ------union all          
 ------ --special invoice return - credit          
 ------ select           
 ------  shopname, ihShopID, ihinvoicedate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
 ------  -(convert(numeric(18,8), sum(idunitprice ))) creditsales,           
 ------  -(convert(numeric(18,8), sum(idunitprice * ihdepexrate))) dcreditsales,           
 ------  -(convert(numeric(18,8), sum(idunitprice * ihexchangerate))) ccreditsales,           
 ------  sum(idcostprice * reqqty) costvalue, sum(idcostprice * reqqty) * ihdepexrate dcostvalue,           
 ------  sum(idcostprice * reqqty) * ihexchangerate ccostvalue,           
 ------  -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) margin, -((convert(numeric(18,8), sum(idunitprice ))) -           
 ------  sum(idcostprice*abs(reqqty))) * ihdepexrate dmargin, -((convert(numeric(18,8),           
 ------  sum(idunitprice ))) -  sum(idcostprice*abs(reqqty))) * ihexchangerate cmargin,           
 ------  0.00,0.00,0.00,0.00,0.00,0.00,departmentname, ihdepartmentid departmentid           
 ------ ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 ------ from           
 ------  losspecialinvoicedetail, losspecialinvoiceheader, ashops s,           
 ------  adepartmentmaster d           
 ------ where           
 ------  ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND           
 ------  IHCANCELLED = 0 and ihproforma = 0 and ihshopid = shopid and           
 ------  ihcashinvoice = 0 and idratetype = 1 and ihtransfinished = 1 and           
 ------  ihdepartmentid = d.departmentid           
 ------ group by           
 ------  shopname, ihshopid, ihdepartmentid, departmentname,          
 ------  ihinvoicedate , ihexchangerate, ihdepexrate,ihInvoiceid          

-- RefNo-3 ends
           
 union all          
           
  select           
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, 0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,0.00,0.00,0.00,  
   -sum(grncostprice*grndquantity) costvalue, - sum(grncostprice*grndquantity) * grnhdepexrate dcostvalue,           
   -sum(grncostprice*grndquantity) * grnhexchangerate ccostvalue,           
   
   - --(convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) - sum(grncostprice*grndquantity)) margin,
   - --(convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) - sum(grncostprice*grndquantity))* grnhdepexRate dmargin,
   - --(convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) - sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,           
   
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))))-  
sum(grncostprice*grndquantity)) margin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -                   
       sum(grncostprice*grndquantity))* grnhdepexRate dmargin,  
   -(convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) -  
        sum(grncostprice*grndquantity)) * grnhExchangeRate cmargin,                   
   0.00,0.00,0.00,
   -convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0)))) GReturn,           
   -convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0))) * grnhdepexRate) dGReturn,           
   -convert(numeric(18,8),(sum(GRNDunitprice-isnull(idItemTaxAmount,0))) * grnhExchangeRate) cGReturn,
   departmentname, grnhdepartmentid departmentid          
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
  ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,
   -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount
  from           
   losgoodsreturnnoteheader , losgoodsreturnnotedetail, ashops s, adepartmentmaster d           
  where           
   GrnhGoodsreturnnoteID = GRNDReturnNoteID and grnhShopid = GRNDShopid AND GrnhCancel =0           
   and grnhshopid = shopid and grnhdepartmentid = d.departmentid           
  group by           
   shopname, grnhshopid, GrnhGoodsreturnnoteDate, departmentname,           
   grnhdepartmentid , grnhexchangerate, grnhdepexrate,GrnhGoodsreturnnoteID          

  --hari added to include the service booking invoice parts replaced items          
 UNION ALL          
 
  --service invoice (cash) 
  select           
   shopname, repinvdshopid, serinvhdate, 
   --convert(numeric(18,8),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))) cashsales,
   --convert(numeric(18,8),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))* seinvhdepexrate) dcashsales,          
   --convert(numeric(18,8),sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate) ccashsales,          
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) cashsales,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales,    
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales,                  

   0.0 creditsales, 0.0 dcreditsales , 0.0 ccreditsales ,
   sum(repinvdcostprice * repinvdqty) costvalue,           
   sum(repinvdcostprice * repinvdqty) * seinvhdepexrate  dcostvalue,           
   sum(repinvdcostprice * repinvdqty) *serinvhcmpexrate ccostvalue,           
   
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),           
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate,
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate,          
   
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
   --   -sum(repinvdcostprice * repinvdqty)margin,             
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
   --   -sum(repinvdcostprice * repinvdqty) *  seinvhdepexrate dmargin,  
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
   --   -sum(repinvdcostprice * repinvdqty) *  serinvhcmpexrate cmargin,            

   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))  
      -sum(repinvdcostprice * repinvdqty)margin,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))  
      -sum(repinvdcostprice * repinvdqty)) *  seinvhdepexrate dmargin,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))  
 -sum(repinvdcostprice * repinvdqty)) *  serinvhcmpexrate cmargin,          

   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, serinvhDepartmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2

 --RefNo-4  start commneted, since this gst amount is taken care in below
  --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount
  --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,
  --convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount
    ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
--RefNo-4 ends
  from           
   losinvoicedpartsreplacedetails, losserviceinvheader, ashops s, adepartmentmaster d           
  where           
   serinvhid = repinvinvoiceid and serinvhshopid = repinvdshopid AND serinvhcancelled=0           
    and repinvdshopid = shopid and serinvhcashacc is not null and serinvhCashInv = 1          
   and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0        
  group by           
   shopname, repinvdshopid, serinvhDepartmentid,           
   departmentname, serinvhdate, serinvhcmpexrate, seinvhdepexrate,serinvhid           
          
 union all          
 
 --service Details (cash)      
  select           
   shopname, serinvhshopid, serinvhdate,
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0))cashsales ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* seinvhdepexrate)dcashsales ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))* serinvhcmpexrate)ccashsales ,           
   --convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))cashsales ,             
   --convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate)dcashsales ,             
   --convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate)ccashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))cashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcashsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-(isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccashsales ,  --RefNo-13 changed bracket         
   
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,               
   0 costvalue, 0 dcostvalue, 0 ccostvalue,           
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)),           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0)) *  serinvhcmpexrate) ,           
   --convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   --convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) ,             
   --convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate,             
   convert(numeric(18,8),serinvhserviceamt-((isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate,             

   
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, serinvhDepartmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount
  ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,
   convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount
  from           
--RefNo-4 start commented below
  -- losserviceinvheader, ashops s, adepartmentmaster d           
  --where           
  -- serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1          
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid     
losserviceinvheader
  inner join  ashops s on serinvhshopid = shopid 
  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
  and serinvhDepartmentid = d.departmentid   and Patindex('%y%',repinvdtype)>0 
 where                   
	serinvhcancelled=0 and serinvhcashacc is not null and serinvhCashInv = 1  
    and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-4 ends 
 
 union all

  --service invoice (credit)        
  select           
   shopname, repinvdshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))) creditsales,                
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* seinvhdepexrate dcreditsales ,             
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))* serinvhcmpexrate ccreditsales ,             

   sum(repinvdcostprice * repinvdqty) costvalue, sum(repinvdcostprice * repinvdqty)*           
   seinvhdepexrate  dcostvalue, sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate ccostvalue,           
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * seinvhdepexrate,  
   --convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty) * serinvhcmpexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0))))-sum(repinvdcostprice * repinvdqty),  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))-sum(repinvdcostprice * repinvdqty)) * seinvhdepexrate,  
   convert(numeric(18,8),(sum((repinvdrate * repinvdqty)-isnull(repinvdItemTaxAmount,0)))-sum(repinvdcostprice * repinvdqty)) * serinvhcmpexrate,  
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, serinvhDepartmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  --RefNo-4  start commneted, since this gst amount is taken care in below
  --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0)))GSTAmount
  --,convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* seinvhdepexrate)dGSTAmount,
  -- convert(numeric(18,8),sum(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount
    ,0 GSTAmount,0 dGSTAmount,0 cGSTAmount
    --RefNo-4  ends
  from           
   losinvoicedpartsreplacedetails, losserviceinvheader,           
   ashops s, adepartmentmaster d 
  where 
	serinvhid = repinvinvoiceid and           
    serinvhshopid = repinvdshopid AND serinvhcancelled=0           
    and repinvdshopid = shopid and serinvhcashacc is null           
   and serinvhCashInv = 0  and serinvhDepartmentid = d.departmentid            
   and Patindex('%y%',repinvdtype)>0        
  group by           
   shopname, repinvdshopid, departmentname, serinvhDepartmentid, serinvhdate, seinvhdepexrate,          
   serinvhcmpexrate ,serinvhid           
  
  union all          
  
--  --service Details          
  select           
   shopname, serinvhshopid, serinvhdate,  0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,           
   --convert(numeric(18,8),serinvhserviceamt- (isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) creditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* seinvhdepexrate) dcreditsales ,             
   --convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))* serinvhcmpexrate) ccreditsales ,             
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))creditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))*seinvhdepexrate dcreditsales ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))))*serinvhcmpexrate ccreditsales ,             
   0 costvalue, 0 dcostvalue, 0 ccostvalue,           
   --convert(numeric(18,8),serinvhserviceamt-isnull(serinvhTaxamount,0)) ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))*seinvhdepexrate) ,           
   --convert(numeric(18,8),(serinvhserviceamt-isnull(serinvhTaxamount,0))*serinvhcmpexrate) ,           
   convert(numeric(18,8),serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0))) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*seinvhdepexrate) ,             
   convert(numeric(18,8),(serinvhserviceamt-(isnull(serinvhTaxamount,0)-isnull(repinvdItemTaxAmount,0)))*serinvhcmpexrate) ,             
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, serinvhDepartmentid departmentid           
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,convert(numeric(18,8),isnull(serinvhTaxamount,0))GSTAmount
  ,convert(numeric(18,8),isnull(serinvhTaxamount,0)* seinvhdepexrate)dGSTAmount,
   convert(numeric(18,8),isnull(serinvhTaxamount,0)* serinvhcmpexrate)cGSTAmount
from  
   --RefNo-4 start commented below         
  -- losserviceinvheader, ashops s, adepartmentmaster d           
  --where           
  -- serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0          
  -- and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid      
  losserviceinvheader
	  inner join  ashops s on serinvhshopid = shopid 
	  inner join  adepartmentmaster d on  serinvhDepartmentid = d.departmentid                   
	  left join losinvoicedpartsreplacedetails det  on  serinvhid = repinvinvoiceid 
	  and serinvhshopid = repinvdshopid AND  repinvdshopid = shopid 
	  and serinvhDepartmentid = d.departmentid and Patindex('%y%',repinvdtype)>0 
 where                   
   serinvhcancelled=0 and serinvhcashacc is null and serinvhCashInv = 0                  
   and serinvhDepartmentid = d.departmentid and serinvhshopid = shopid   
 --RefNo-4 ends

  union all          
         
  --FOR REXOPRTING INVOCIE FOR CUSTOMERS AND VENDORS  -- 22/12/2002          
  --credit          
 
  select           
   shopname, REhShopID, rehExportdate, 0.0 cashsales, 0.0 cashsales,           
   0.0 ccashsales,          
   convert(numeric(18,8), sum(redunitprice)) creditsales,           
   convert(numeric(18,8), sum(redunitprice * rehdepexrate))  dcreditsales, 
   convert(numeric(18,8), sum(redunitprice * rehexchangerate)) ccreditsales, sum(redcostprice * redquantity) costvalue,           
   sum(redcostprice * redquantity) * rehdepexrate dcostvalue, sum(redcostprice * redquantity) *           
   rehexchangerate ccostvalue,  (convert(numeric(18,8), sum(redunitprice ))) -           
   sum(redcostprice * redquantity) margin, (convert(numeric(18,8), sum(redunitprice * rehdepexrate))) -           
   sum(redcostprice * redquantity) * rehdepexrate dmargin,(convert(numeric(18,8),           
   sum(redunitprice * rehexchangerate))) - sum(redcostprice * redquantity) * rehexchangerate cmargin,           
   0.00,0.00,0.00,0.00,0.00,0.00,departmentname, rehdepartmentid          
  ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
  ,0.0 GSTAmount ,0.0 dGSTAmount,0.0 cGSTAmount
  from           
   losExportDetail, losExportHeader, ashops s, adepartmentmaster d           
  where           
   rehExportID = redExportID and rehshopid = redshopid AND           
   reHCANCELLED=0 and rehtype ='i' and          
   rehproforma=0 and rehshopid = shopid and rehcashinvoice=0 and           
   rehdepartmentid = d.departmentid           
  group by           
   shopname, rehshopid, departmentname, rehdepartmentid, rehExportDate,           
   rehdepexrate, rehexchangerate,rehExportID           
          
 union all          
 -- added From Vwcashsales -Margin Not calculating          
           
 select           
  s.shopname, vws.sishopid, vws.siinvoicedate,           
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,           
  --convert(numeric(18,8),sum(vws.siamount * aidepexrate)) as  dcashsales,           
  --convert(numeric(18,8),sum(vws.siamount * aiexchangerate)) as ccashsales,  
  convert(numeric(18,8),sum(vws.sidamount)) as  dcashsales,  
  convert(numeric(18,8),sum(vws.sicamount)) as ccashsales,   
   0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,           
   0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,          
  convert(numeric(18,8),sum(vws.siamount)) as cashsales,           
  --convert(numeric(18,8),sum(vws.siamount * aidepexrate)) as  dcashsales,           
  --convert(numeric(18,8),sum(vws.siamount * aiexchangerate)) as ccashsales, 
  convert(numeric(18,8),sum(vws.sidamount))as  dmargin,  
  convert(numeric(18,8),sum(vws.sicamount))as cmargin,  
  0.00,0.00,0.00,0.00,0.00,0.00,d.departmentname,lah.aidepartmentid  departmentid           
 ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
 , sum(vws.GSTAmount)as GSTAmount
 , sum(vws.dGSTAmount)as dGSTAmount
 , sum(vws.cGSTAmount)as cGSTAmount
 from           
  vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d ,ashops s          
 where           
  aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and           
  aishopid = sishopid and lah.aicashinvoice=1 and           
  lah.aidepartmentid =d.departmentid and s.departmentid = d.departmentid          
  and aiShopId = s.ShopId          
 group by           
  s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid, vws.siinvoicedate          
          
 union all          
          
    select s.shopname, vws.sishopid, vws.siinvoicedate,           
    0.0 creditsales, 0.0 dcreditsales, 0.0 ccreditsales,           
    convert(numeric(18,8),sum(vws.siamount)) as  creditsales,           
    --convert(numeric(18,8),sum(vws.siamount * aidepexrate)) as   dcreditsales,           
    --convert(numeric(18,8),sum(vws.siamount * aiexchangerate)) as ccreditsales,  
    convert(numeric(18,8),sum(vws.sidamount)) as  dcreditsales,  
	convert(numeric(18,8),sum(vws.sicamount)) as ccreditsales,   
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,          
    convert(numeric(18,8),sum(vws.siamount)) as  margin,           
    --convert(numeric(18,8),sum(vws.siamount * aidepexrate)) as   dmargin,           
    --convert(numeric(18,8),sum(vws.siamount * aiexchangerate)) as cmargin,          
    convert(numeric(18,8),sum(vws.sidamount))as dmargin,  
    convert(numeric(18,8),sum(vws.sicamount))as cmargin,  
    0.00,0.00,0.00,0.00,0.00,0.00,d.departmentname,lah.aidepartmentid  departmentid           
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
    , sum(vws.GSTAmount)as GSTAmount
     , sum(vws.dGSTAmount)as dGSTAmount
	 , sum(vws.cGSTAmount)as cGSTAmount
    from vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah,adepartmentmaster d,ashops s          
    where aiinvoiceid=siinvoiceid and aicancelled=0 and aiproforma=0 and           
    aishopid = sishopid and lah.aicashinvoice=0 and lah.aidepartmentid =d.departmentid          
    and s.departmentid = d.departmentid and s.ShopId = aiShopId group by               
    s.shopname, vws.sishopid, d.departmentname, lah.aidepartmentid,vws.siinvoicedate,aiinvoiceid           
           
    UniOn All -- added from vwCashSales         
    --Shop debit credit notes and handling debit notes which are debit to the        
    -- customer and hence act as invoices to be settled              
    Select  s.shopname,losdcnshopid,losdcndate,      
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,          
    COnvert(numeric(18,8),Sum(losDCNAmount))  creditsales,             
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dcreditsales,       
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  ccreditsales,       
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                   
    COnvert(numeric(18,8),Sum(losDCNAmount))  margin,             
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  dmargin,       
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  cmargin,      
    0.00,0.00,0.00,0.00,0.00,0.00,d.departmentname,losdcndepartmentid           
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
     ,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount
    From Ashops s,  losdebitcreditnote, adepartmentmaster d       
    Where  s.shopid = losdcnshopid And s.accountable Is Not Null           
    And d.DepartmentID = losdcndepartmentid And losdcncancelled =0            
    And losdcndebit =1  Group By s.shopname,d.departmentname,losdcnshopid,          
    losdcndate, losdepexrate, losexchangerate,losdcndepartmentid      
      
    --hq serivce invoice dOne for shop            
    Union all      
       
    Select  null, 0,ai.invoicedate,      
    0.0 cashsales, 0.0 dcashsales, 0.0 ccashsales,          
	COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  creditsales,               
	COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dcreditsales,         
	COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)ccreditsales,         
    0.0 costvalue, 0.0  dcostvalue,0.0 ccostvalue,                   
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))margin,             
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)dmargin,       
    COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)) * exchangerate)cmargin,      

    0.00,0.00,0.00,0.00,0.00,0.00,d.departmentname,ai.departmentid   
    ,0.0 PdChequeSales, 0.0 dPdChequeSales,0.0 cPdChequeSales --RefNo-2
    ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount 
    ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,
     convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount

    From accountsinvoiceheader ai, serviceinvoicedetails ser ,adepartmentmaster d       
    Where ai.invoiceid = ser.invoiceid And ai.companyid =             
    ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0     
    and ai.departmentid = d.departmentid and ai.companyid = d.companyid       
    Group By  ai.invoicedate,depexrate,exchangerate,      
    d.departmentname,ai.departmentid          
          
 ) cashcreditcollection          
group by           
 cashcreditcollection.shopname, cashcreditcollection.poshshopid,           
 cashcreditcollection.departmentname, cashcreditcollection.departmentid,           
 cashcreditcollection.poshbilldate          
          
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Update DescriptionNew Report-> Sales and Collection Summary GST Separately from bijesh on 27.09.2012
------from bijesh
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollection_shopwiseGSTSeparately')
   DROP view dbo.vwDailySalesCollection_shopwiseGSTSeparately
GO
    

--Last Modified on  : 12/12/02, 01/11/2004                        
--Modified by  : leo, Hariharan                           
--Comments  : v3                          
--          : Removed VwCashSalesTruncated as max tables error (256 tables) was coming                           
--          : while executing query with this view. Made vwCashSales to Refer Only Once                     
--Modified By: Benzigar S D                  
--Modified On: 23/03/2009                  
--Comments   : Added exchange rate amount in receipts               
----------------------------------------------------------------------------------------------                  
--Modified By: Regin Thangaraj        
--Modified On: 26/10/2010        
--Comments   : Corrected receipt amount calculation (RefNo-1)        
----------------------------------------------------------------------------------------------   
-- RefNo-1 this view is userd for rptdailysalescollectionshopwise report.shop wise recipt is not showing   
--correct  in this vwDailySalesCollection  .  so i have created vwDailySalesCollection_shopwise  view  
--jyothish 2-2-2011    
----------------------------------------------------------------------------------------------   
--RefNo        : RefNo-2
--Modified by  : Bijesh.B
--Date         : 12/06/2011
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)
----------------------------------------------------------------------------------------------  
--RefNo        : RefNo-3
--Modified by  : SHINE DAS
--Date         : 27/07/2011
--Comments     : The code added for RefNo-1 was wrong. So commented it, and
--uncommented the old one.
----------------------------------------------------------------------------------------------  
--RefNo        : RefNo-4
--Modified by  : Bijesh.B
--Date         : 03/07/2011
--Comments     : Bugsheet (P & C/REPORTS/PandC report.xls) against ticket id CBN-603540
--               (defect id 33)  
----------------------------------------------------------------------------------------------  
----------------------------------------------------------------------------------------------       
--RefNo        : New View and Report
--Created by   : Bijesh.B 
--Date         : 11/04/2012
--Ticket id    : JDJ-400367 (new report (rtdailysalescollectionshopwiseGSTSeparately) for sonee - GST separation)
--Comments     : Created new view and report (Copy of vwDailySalesCollection_shopwise)
----------------------------------------------------------------------------------------------       
--Modified by   : Bijesh.B 
--Date          : 16/07/2012
--Ticket id     : JDJ-400367 
--Desc          : correctd values
----------------------------------------------------------------------------------------------       

CREATE VIEW dbo.vwDailySalesCollection_shopwiseGSTSeparately AS                          
                          
select companyid,departmentid, shopid, billdate,                           
convert(numeric(18, 8), sum(cashsales)) cashsales,                           
convert(numeric(18, 8), sum(dcashsales)) dcashsales,                           
convert(numeric(18, 8), sum(ccashsales)) ccashsales,                           
convert(numeric(18, 8), sum(receipts)) receipts,                           
convert(numeric(18, 8), sum(dreceipts)) dreceipts,                           
convert(numeric(18, 8), sum(creceipts)) creceipts,                           
convert(numeric(18, 8), sum(payments)) payments ,                          
convert(numeric(18, 8), sum(dpayments)) dpayments ,                           
convert(numeric(18, 8), sum(cpayments)) cpayments ,                          
convert(numeric(18, 8), sum(creditsales)) creditsales,                           
convert(numeric(18, 8), sum(dcreditsales)) dcreditsales,                           
convert(numeric(18, 8), sum(ccreditsales)) ccreditsales,                           
convert(numeric(18, 8), sum(creditcard)) as creditcard,                           
convert(numeric(18, 8), sum(dcreditcard)) as dcreditcard,                           
convert(numeric(18, 8), sum(ccreditcard)) as ccreditcard,                           
convert(numeric(18, 8), sum(debitcard)) as debitcard,                          
convert(numeric(18, 8), sum(ddebitcard)) as ddebitcard,                           
convert(numeric(18, 8), sum(cdebitcard)) as cdebitcard,                          
convert(numeric(18, 8), sum(localpurchase)) as localpurchase,                           
convert(numeric(18, 8), sum(dlocalpurchase)) as dlocalpurchase,                          
convert(numeric(18, 8), sum(clocalpurchase)) as clocalpurchase 
--RefNo-2 start -------------------
,convert(numeric(18, 8), sum(PdChequeSales)) PdChequeSales,                           
convert(numeric(18, 8), sum(dPdChequeSales)) dPdChequeSales,                           
convert(numeric(18, 8), sum(cPdChequeSales)) cPdChequeSales
--RefNo-2 end -------------------         
,convert(numeric(18,8),sum(GSTAmount))GSTAmount,
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount
from                          
(select cs.companyid ,departmentid, shopid, billdate,                         
case when cash=1 and (am.misc='CA' or am.misc is null) then sum(Amount) else 0 end cashsales,                           
case when cash=1 and (am.misc='CA' or am.misc is null) then sum(damount) else 0 end  dcashsales,                         
case when cash=1 and (am.misc='CA' or am.misc is null) then sum(camount) else 0 end  ccashsales,                        
case when cash=1 and am.misc='CC' then sum(Amount) else 0 end creditcard,                           
case when cash=1 and am.misc='CC' then sum(damount) else 0 end  dcreditcard,                         
case when cash=1 and am.misc='CC' then sum(camount) else 0 end  ccreditcard,                        
case when cash=1 and am.misc='DC' then sum(Amount) else 0 end debitcard,                           
case when cash=1 and am.misc='DC' then sum(damount) else 0 end  ddebitcard,                         
case when cash=1 and am.misc='DC' then sum(camount) else 0 end  cdebitcard,                        
0.0 as receipts, 0.0 as dreceipts, 0.0 as creceipts,                         
0.0 as payments, 0.0 as dpayments, 0.0 as cpayments,   

--RefNo-2 start commented below -----------------------------                      
/*
case when cash=0 then sum(Amount) else 0 end creditsales,                           
case when cash=0 then sum(damount) else 0 end  dcreditsales,                         
case when cash=0 then sum(camount) else 0 end  ccreditsales,                        
*/
case when cash=0 and (transtype<>'PD CHEQUE') then sum(Amount) else 0 end creditsales,                           
case when cash=0 and (transtype<>'PD CHEQUE') then sum(damount) else 0 end  dcreditsales,                         
case when cash=0 and (transtype<>'PD CHEQUE') then sum(camount) else 0 end  ccreditsales,                        
--RefNo-2 ends ----------------------------------------------
0.0 as localpurchase,                           
0.0 as dlocalpurchase , 0.0 as clocalpurchase                            
--RefNo-2 start ---------------------------------------------                      
,case when cash=0 and (transtype='PD CHEQUE') then sum(Amount) else 0 end PdChequeSales,                     
case when cash=0 and (transtype='PD CHEQUE') then sum(damount) else 0 end dPdChequeSales,                   
case when cash=0 and (transtype='PD CHEQUE') then sum(camount) else 0 end cPdChequeSales                  
--RefNo-2 ends ---------------------------------------------                      
,sum(GSTAmount)GSTAmount,sum(dGSTAmount)dGSTAmount,sum(cGSTAmount)cGSTAmount
from vwCAshSalesGSTSeparately cs left outer join aaccountmaster am   on                        
cs.accountid = am.accountid and cs.companyid = am.companyid                      
group by cs.companyid ,departmentid, shopid, billdate, am.misc, cash -- cashsales                           
,transtype --RefNo2                   
          
union all                          

select drcompanyid, drdepartmentid, drshopid, drdate, 0.0 as cashsales, 0.0 as dcashsales,                           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,                           
0.0 as ddebitcard, 0.0 as cdebitcard,                           
convert(numeric(18,8),sum(drAmount)) receipts,                           
convert(numeric(18,8),sum(drAmount)* drdepexrate) dreceipts,                           
convert(numeric(18,8),sum(drAmount)*drexchangerate) creceipts,                           
0.0 as payments, 0.0 as dpayments,                       
0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales,                           
0.0 as ccreditsales, 0.0 as localpurchase,                          
0.0 as dlocalpurchase, 0.0 as clocalpurchase
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
--RefNo-2 end -------------------      
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount                        
from losDummyReceiptHeader rh, acustomermaster cm                         
where drcancelled = 0                           
and rh.drcustomerid = cm.customerid                           
and rh.drcompanyid = cm.companyid                           
group by drcompanyid, drdepartmentid, drshopid, drdate                          
,drdepexrate,drexchangerate
-- RefNo-4 start  below commented since in shopwise report, they don't need receipts done
-- in Accounts
/*                           
union all                           
                         
--selects the receipts done in the HQ for the shop other than the shop receipts by checking the                           
--exchange nature field. iF THE exchangenature field is null then the receipt is done only in                           
--hq and if the exchangenature field is not null then the shop receipts will only taken                          
--for receipts                          
select rh.companyid, rh.departmentid, rd.shopid, rh.receiptdate, 0.0 as cashsales,                           
0.0 as dcashsales,                           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,                           
0.0 as ddebitcard, 0.0 as cdebitcard,                           
--convert(numeric(18,8),sum(rd.AmountReceived)) receipts,                           
--convert(numeric(18,8),sum(rd.AmountReceived )) dreceipts,                           
--convert(numeric(18,8),sum(rd.AmountReceived )) creceipts,              
------------------ Benzigar code -------------------------------------------                  
convert(numeric(18,8),sum(rh.customeramount)) receipts,                           
convert(numeric(18,8),sum(rh.Amount*rh.depexrate )) dreceipts,                           
convert(numeric(18,8),sum(rh.Amount*rh.exchangerate)) creceipts,                
-------------------------------------------------------------                
--Commented below section for RefNo-3
 --Corrected receipt amount calculation. Old code commented above. (RefNo-1)        
----convert(numeric(18,8),sum(rd.AmountReceived)) receipts,                           
----convert(numeric(18,8),sum(rd.AmountReceived*rh.depexrate)) dreceipts,                           
----convert(numeric(18,8),sum(rd.AmountReceived*rh.exchangerate)) creceipts,         
0.0 as payments,          
0.0 as dpayments,                           
0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales, 0.0 as ccreditsales,                           
0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase                             
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
--RefNo-2 ends -------------------
from receiptvoucherheader rh, receiptvoucherdetails rd                           
where rh.receiptid = rd.receiptid                           
and rh.companyid = rd.companyid                 
and rh.cancelled=0                          
and ((rh.dummyreceiptid is null and rh.recshopid is null)                           
      or (rh.dummyreceiptid=0 and rh.recshopid=0))                        
group by rh.companyid,rh.departmentid, rd.shopid, rh.receiptdate                          
                    
union all                       
-- For Populating Other Receipts                     
-- Other Receipts is done in Departments So ShopId will be 0                    
select rh.companyid, rh.departmentid, 0 shopid, rh.receiptdate, 0.0 as cashsales,      
0.0 as dcashsales,                           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,                           
0.0 as ddebitcard, 0.0 as cdebitcard,                           
convert(numeric(18,8),sum(Amount)) receipts,                           
convert(numeric(18,8),sum(Amount * depexrate)) dreceipts,                           
convert(numeric(18,8),sum(Amount* exchangerate)) creceipts, 0.0 as payments,                           
0.0 as dpayments,                           
0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales, 0.0 as ccreditsales,                           
0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase                             
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
--RefNo-2 ends -------------------
from receiptvoucherheader rh                          
where  rh.cancelled=0                     
and rh.ReceiptID not in (select ReceiptID from ReceiptVoucherDetails)                       
and ((rh.dummyreceiptid is null and rh.recshopid is null)                           
      or (rh.dummyreceiptid=0 and rh.recshopid=0))                
group by rh.companyid,rh.departmentid, rh.receiptdate                    

*/
-- RefNo-4 ends
                     
union all                          
                          
select phcompanyid,phdepartmentid, phshopid, phPaymentDate, 0.0 as cashsales, 0.0 as dcashsales,                           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,                           
0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts, 0.0 as creceipts,                           
convert(numeric(18,8),sum(phAmount)) as payments,                           
convert(numeric(18,8),sum(phAmount)* phdepexrate) as dpayments,                           
convert(numeric(18,8),sum(phAmount)* phexchangerate) as cpayments,                           
0.0 as creditsales , 0.0 as dcreditsales, 0.0 as ccreditsales, 0.0 as localpurchase,                           
0.0 as dlocalpurchase, 0.0 as clocalpurchase                             
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
--RefNo-2 ends -------------------
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
from LOsPaymentVoucherHeader ph                           
where phcancelled = 0                            
group by phcompanyid, phdepartmentid, phshopid, phPaymentDate                          
,phdepexrate, phexchangerate                         
union all                          
--local purchase - madhu 23/08/01   
                       
--select lh.lphcompanyid,lh.lphdepartmentid,lh.lphshopid,lh.lphbilldate, 0.0 cashsales,                           
--0.0 dcashsales, 0.0 ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard,                          
--0.0 as debitcard, 0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts,              
--0.0 as creceipts, 0.0 as payments, 0.0 as dpayments, 0.0 as cpayments, 0.0 as creditsales,                           
--0.0 as dcreditsales, 0.0 as ccreditsales, convert(numeric(18,8),sum(lphbillamount)) as localpurchase,                          
--convert(numeric(18,8),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,                           
--convert(numeric(18,8),sum(lphbillamount*lphexchangerate)) as clocalpurchase                          
----RefNo-2 start -------------------
--,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
--0.0 as cPdChequeSales
----RefNo-2 ends -------------------
--,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
--from loslocalpurchaseheader lh,adepartmentmaster d where                          
--lh.lphDepartmentID=d.departmentid  and lh.lphcashpurchase=1  and lphcancelled=0                          
--group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate) summary                           
--group by companyid ,departmentid, shopid, billdate 

select lh.lphcompanyid,lh.lphdepartmentid,lh.lphshopid,lh.lphbilldate, 0.0 cashsales,                           
0.0 dcashsales, 0.0 ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard,                          
0.0 as debitcard, 0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts,              
0.0 as creceipts, 0.0 as payments, 0.0 as dpayments, 0.0 as cpayments, 0.0 as creditsales,                           
0.0 as dcreditsales, 0.0 as ccreditsales,
--convert(numeric(18,8),sum(lphbillamount)) as localpurchase1,                          
--convert(numeric(18,8),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,                           
--convert(numeric(18,8),sum(lphbillamount*lphexchangerate)) as clocalpurchase                          
convert(numeric(18,8),sum(lphbillamount-isnull(ld.lpdItemTaxAmount,0))) as localpurchase,   
convert(numeric(18,8),sum(lphbillamount-isnull(ld.lpdItemTaxAmount,0))* lphdepexrate) as dlocalpurchase,                           
convert(numeric(18,8),sum(lphbillamount-isnull(ld.lpdItemTaxAmount,0))*lphexchangerate) as clocalpurchase                          

--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
--RefNo-2 ends -------------------
,convert(numeric(18,8),sum(isnull(ld.lpdItemTaxAmount,0))) as GSTAmount,
convert(numeric(18,8),sum(isnull(ld.lpdItemTaxAmount,0))*lphdepexrate) as dGSTAmount,
convert(numeric(18,8),sum(isnull(ld.lpdItemTaxAmount,0))*lphexchangerate) as cGSTAmount
from loslocalpurchaseheader lh,adepartmentmaster d,
(select lpdShopID,lpdBillID , SUM(isnull(lpdItemTaxAmount,0))lpdItemTaxAmount 
 from loslocalpurchaseDetail group by lpdShopID,lpdBillID)ld
where                          
lh.lphDepartmentID=d.departmentid and lh.lphcashpurchase=1  and lphcancelled=0 
and lh.lphBillID = ld.lpdBillID and lh.lphShopID = ld.lpdShopID                            
group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate
,lphdepexrate,lphexchangerate
) summary                           
group by companyid ,departmentid, shopid, billdate 



GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Update Description 	New Report-> Sales and Collection Summary GST Separately from bijesh on 27.09.2012 from bijesh
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionGSTSeparately')
   DROP view dbo.vwDailySalesCollectionGSTSeparately
GO
--Last Modified on  : 12/12/02, 01/11/2004                        
--Modified by  : leo, Hariharan                           
--Comments  : v3                          
--          : Removed VwCashSalesTruncated as max tables error (256 tables) was coming                           
--          : while executing query with this view. Made vwCashSales to Refer Only Once                     
--Modified By: Benzigar S D                  
--Modified On: 23/03/2009                  
--Comments   : Added exchange rate amount in receipts               
----------------------------------------------------------------------------------------------                  
--Modified By: Regin Thangaraj        
--Modified On: 26/10/2010        
--Comments   : Corrected receipt amount calculation (RefNo-1)        
----------------------------------------------------------------------------------------------                  
--RefNo        : RefNo-2      
--Modified by  : Bijesh.B      
--Date         : 12/06/2011      
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)      
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-3      
--Modified by  : Bijesh.B      
--Date         : 31/08/2011      
--Comments     : Bugsheet (P & C/REPORTS/PandC report.xls) against ticket id CBN-603540      
--               (defect id 59) - No need to show Dummy Receipt amount with Department wise option      
----------------------------------------------------------------------------------------------        
--RefNo        : RefNo-4     
--Modified by  : AADYAKUMAR.D.V  
--Date         : 12/12/2011      
--Comments     : As per ticket NRT-913015 i am modified  
----------------------------------------------------------------------------------------------     
----------------------------------------------------------------------------------------------       
--RefNo        : Created New View 
--Created by   : Bijesh.B 
--Date         : 11/04/2012
--Ticket id    : JDJ-400367 (new report (rptdailysalescollectiondepwiseGSTSeparately) for sonee - GST separation)
--Comments     : Created new view and report (Copy of vwDailySalesCollection)
----------------------------------------------------------------------------------------------       
--RefNo        : RefNo-5     
--Modified by  : AADYAKUMAR.D.V  
--Date         : 07/05/2012
--Comments     : Added new column to synchronize with report
----------------------------------------------------------------------------------------------     
--Modified by   : Bijesh.B 
--Date          : 16/07/2012
--Ticket id     : JDJ-400367 
--Desc          : correctd values
----------------------------------------------------------------------------------------------       

create VIEW dbo.vwDailySalesCollectionGSTSeparately AS                          
                          
select companyid,departmentid, shopid, billdate,                           
convert(numeric(18,8), sum(cashsales)) cashsales,                           
convert(numeric(18,8), sum(dcashsales)) dcashsales,                           
convert(numeric(18,8), sum(ccashsales)) ccashsales,                           
convert(numeric(18,8), sum(receipts)) receipts,                           
convert(numeric(18,8), sum(dreceipts)) dreceipts,                           
convert(numeric(18,8), sum(creceipts)) creceipts,                           
convert(numeric(18,8), sum(payments)) payments ,                          
convert(numeric(18,8), sum(dpayments)) dpayments ,                           
convert(numeric(18,8), sum(cpayments)) cpayments ,                          
convert(numeric(18,8), sum(creditsales)) creditsales,                           
convert(numeric(18,8), sum(dcreditsales)) dcreditsales,                           
convert(numeric(18,8), sum(ccreditsales)) ccreditsales,                           
convert(numeric(18,8), sum(creditcard)) as creditcard,                           
convert(numeric(18,8), sum(dcreditcard)) as dcreditcard,                           
convert(numeric(18,8), sum(ccreditcard)) as ccreditcard,                           
convert(numeric(18,8), sum(debitcard)) as debitcard,                          
convert(numeric(18,8), sum(ddebitcard)) as ddebitcard,                           
convert(numeric(18,8), sum(cdebitcard)) as cdebitcard,                          
convert(numeric(18,8), sum(localpurchase)) as localpurchase,                           
convert(numeric(18,8), sum(dlocalpurchase)) as dlocalpurchase,                          
convert(numeric(18,8), sum(clocalpurchase)) as clocalpurchase,
-- RefNo-5  
convert(numeric(18,8), sum(Exchange)) as Exchange,           
convert(numeric(18,8), sum(dExchange)) as dExchange,  
convert(numeric(18,8), sum(cExchange)) as cExchange,  
convert(numeric(18,8), sum(GoodsReturn)) as GoodsReturn,           
convert(numeric(18,8), sum(dGoodsReturn)) as dGoodsReturn,  
convert(numeric(18,8), sum(cGoodsReturn)) as cGoodsReturn 
-- RefNo-5      
--RefNo-2 start -------------------      
,convert(numeric(18,8), sum(PdChequeSales)) PdChequeSales,                                 
convert(numeric(18,8), sum(dPdChequeSales)) dPdChequeSales,                                 
convert(numeric(18,8), sum(cPdChequeSales)) cPdChequeSales      
--RefNo-2 end -------------------                             
,convert(numeric(18,8),sum(GSTAmount))GSTAmount,
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount
  
from                          
(select cs.companyid ,departmentid, shopid, billdate,                         
case when cash=1 and (am.misc='CA' or am.misc is null) then sum(Amount) else 0 end cashsales,                           
case when cash=1 and (am.misc='CA' or am.misc is null) then sum(damount) else 0 end dcashsales,                         
case when cash=1 and (am.misc='CA' or am.misc is null) then sum(camount) else 0 end  ccashsales,                        
case when cash=1 and am.misc='CC' then sum(Amount) else 0 end creditcard,                           
case when cash=1 and am.misc='CC' then sum(damount) else 0 end  dcreditcard,                         
case when cash=1 and am.misc='CC' then sum(camount) else 0 end  ccreditcard,                        
case when cash=1 and am.misc='DC' then sum(Amount) else 0 end debitcard,                           
case when cash=1 and am.misc='DC' then sum(damount) else 0 end  ddebitcard,                         
case when cash=1 and am.misc='DC' then sum(camount) else 0 end  cdebitcard,                        
0.0 as receipts, 0.0 as dreceipts, 0.0 as creceipts,                         
0.0 as payments, 0.0 as dpayments, 0.0 as cpayments,      
      
--RefNo-2 start commented below -----------------------------                            
/*      
case when cash=0 then sum(Amount) else 0 end creditsales,                           
case when cash=0 then sum(damount) else 0 end  dcreditsales,                         
case when cash=0 then sum(camount) else 0 end  ccreditsales,                        
*/      
case when cash=0 and (transtype<>'PD CHEQUE') then sum(Amount) else 0 end creditsales,                                 
case when cash=0 and (transtype<>'PD CHEQUE') then sum(damount) else 0 end  dcreditsales,                               
case when cash=0 and (transtype<>'PD CHEQUE') then sum(camount) else 0 end  ccreditsales,                              
--RefNo-2 ends ----------------------------------------------      
0.0 as localpurchase,                           
0.0 as dlocalpurchase , 0.0 as clocalpurchase                            
--RefNo-2 start ---------------------------------------------  
-- RefNo-5  
,0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn 
-- RefNo-5                            
,case when cash=0 and (transtype='PD CHEQUE') then sum(Amount) else 0 end PdChequeSales,                           
case when cash=0 and (transtype='PD CHEQUE') then sum(damount) else 0 end dPdChequeSales,                         
case when cash=0 and (transtype='PD CHEQUE') then sum(camount) else 0 end cPdChequeSales                        
--RefNo-2 ends ---------------------------------------------                            
,sum(GSTAmount)GSTAmount,sum(dGSTAmount)dGSTAmount,sum(cGSTAmount)cGSTAmount
--,case when cash=1 then sum(GSTAmount) else 0 end  GSTAmount,
--case when cash=1 then sum(dGSTAmount) else 0 end  dGSTAmount,
--case when cash=1 then sum(cGSTAmount) else 0 end  cGSTAmount

from vwCAshSalesGSTSeparately cs left outer join aaccountmaster am   on                        
cs.accountid = am.accountid and cs.companyid = am.companyid                      
group by cs.companyid ,departmentid, shopid, billdate, am.misc, cash -- cashsales                           
,transtype --RefNo2                      
          
union all                          
      
select drcompanyid, drdepartmentid, drshopid, drdate, 0.0 as cashsales, 0.0 as dcashsales,                           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,                           
0.0 as ddebitcard, 0.0 as cdebitcard,                           
convert(numeric(18,8),sum(drAmount)) receipts,                           
convert(numeric(18,8),sum(drAmount)* drdepexrate) dreceipts,                           
convert(numeric(18,8),sum(drAmount)*drexchangerate) creceipts,                           
0.0 as payments, 0.0 as dpayments,                       
0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales,                           
0.0 as ccreditsales, 0.0 as localpurchase,                   
0.0 as dlocalpurchase, 0.0 as clocalpurchase,
-- RefNo-5  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn 
-- RefNo-5                            
--RefNo-2 start -------------------      
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                                 
0.0 as cPdChequeSales      
--RefNo-2 end -------------------                                
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
from losDummyReceiptHeader rh, acustomermaster cm                         
where       
drcancelledremarks='Accounted' and  -- RefNo-3 added      
drcancelled = 0                           
and rh.drcustomerid = cm.customerid                           
and rh.drcompanyid = cm.companyid                           
group by drcompanyid, drdepartmentid, drshopid, drdate                          
,drdepexrate,drexchangerate      
union all                           
                         
--selects the receipts done in the HQ for the shop other than the shop receipts by checking the                           
--exchange nature field. iF THE exchangenature field is null then the receipt is done only in                           
--hq and if the exchangenature field is not null then the shop receipts will only taken                          
--for receipts                          
select rh.companyid, rh.departmentid, rd.shopid, rh.receiptdate, 0.0 as cashsales,                           
0.0 as dcashsales,                           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,                           
0.0 as ddebitcard, 0.0 as cdebitcard,                           
--convert(numeric(18,8),sum(rd.AmountReceived)) receipts,                           
--convert(numeric(18,8),sum(rd.AmountReceived )) dreceipts,                           
--convert(numeric(18,8),sum(rd.AmountReceived )) creceipts,   
--RefNo-4  --------------------------start--------------------------------------             
------------------ Benzigar code -------------------------------------------  
--convert(numeric(18,8),sum(rh.customeramount)) receipts,                         
--convert(numeric(18,8),sum(rh.Amount*rh.depexrate )) dreceipts,                         
--convert(numeric(18,8),sum(rh.Amount*rh.exchangerate)) creceipts,                
convert(numeric(18,8),sum(rd.amountreceived)) receipts,                           
convert(numeric(18,8),sum(rd.amountreceived)*rh.depexrate) dreceipts,                           
convert(numeric(18,8),sum(rd.amountreceived)*rh.exchangerate) creceipts,                
-------------------------------------------------------------                
--RefNo-4  ---------------------------end---------------------------------------  
-- Corrected receipt amount calculation. Old code commented above. (RefNo-1)        
--convert(numeric(18,8),sum(rd.AmountReceived)) receipts,                           
--convert(numeric(18,8),sum(rd.AmountReceived*rh.depexrate)) dreceipts,                           
--convert(numeric(18,8),sum(rd.AmountReceived*rh.exchangerate)) creceipts,         
0.0 as payments,                           
0.0 as dpayments,                           
0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales, 0.0 as ccreditsales,                           
0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase,
-- RefNo-5  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn
-- RefNo-5                               
--RefNo-2 start -------------------      
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                                 
0.0 as cPdChequeSales      
--RefNo-2 end -------------------     
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
from receiptvoucherheader rh, receiptvoucherdetails rd                           
where rh.receiptid = rd.receiptid                           
and rh.companyid = rd.companyid                          
and rh.cancelled=0                          
and ((rh.dummyreceiptid is null and rh.recshopid is null)                           
      or (rh.dummyreceiptid=0 and rh.recshopid=0))                        
group by rh.companyid,rh.departmentid, rd.shopid, rh.receiptdate                    
,depexrate,exchangerate                    
union all                       
-- For Populating Other Receipts                     
-- Other Receipts is done in Departments So ShopId will be 0                    
select rh.companyid, rh.departmentid, 0 shopid, rh.receiptdate, 0.0 as cashsales,                           
0.0 as dcashsales,                           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,                           
0.0 as ddebitcard, 0.0 as cdebitcard,                           
convert(numeric(18,8),sum(Amount)) receipts,                           
convert(numeric(18,8),sum(Amount) * depexrate) dreceipts,                           
convert(numeric(18,8),sum(Amount)* exchangerate) creceipts, 0.0 as payments,                           
0.0 as dpayments,                           
0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales, 0.0 as ccreditsales,                           
0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase,
-- RefNo-5  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn
-- RefNo-5                               
--RefNo-2 start -------------------      
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                                 
0.0 as cPdChequeSales     
--RefNo-2 end -------------------                                
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount   
from receiptvoucherheader rh                          
where  rh.cancelled=0                     
and rh.ReceiptID not in (select ReceiptID from ReceiptVoucherDetails)                       
and ((rh.dummyreceiptid is null and rh.recshopid is null)                           
      or (rh.dummyreceiptid=0 and rh.recshopid=0))                
group by rh.companyid,rh.departmentid, rh.receiptdate                    
,depexrate, exchangerate                    
union all                          
                          
select phcompanyid,phdepartmentid, phshopid, phPaymentDate, 0.0 as cashsales, 0.0 as dcashsales,                           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,                           
0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts, 0.0 as creceipts,                      
convert(numeric(18,8),sum(phAmount)) as payments,                           
convert(numeric(18,8),sum(phAmount)* phdepexrate) as dpayments,                           
convert(numeric(18,8),sum(phAmount)* phexchangerate) as cpayments,                           
0.0 as creditsales , 0.0 as dcreditsales, 0.0 as ccreditsales, 0.0 as localpurchase,                           
0.0 as dlocalpurchase, 0.0 as clocalpurchase,
-- RefNo-5  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                             
-- RefNo-5  
--RefNo-2 start -------------------      
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                                 
0.0 as cPdChequeSales      
--RefNo-2 end -------------------      
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
from LOsPaymentVoucherHeader ph                           
where phcancelled = 0                      
group by phcompanyid, phdepartmentid, phshopid, phPaymentDate                          
,phdepexrate,phexchangerate                          
union all                          
--local purchase - madhu 23/08/01                          
--select lh.lphcompanyid,lh.lphdepartmentid,lh.lphshopid,lh.lphbilldate, 0.0 cashsales,                           
--0.0 dcashsales, 0.0 ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard,                          
--0.0 as debitcard, 0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts,                          
--0.0 as creceipts, 0.0 as payments, 0.0 as dpayments, 0.0 as cpayments, 0.0 as creditsales,                           
--0.0 as dcreditsales, 0.0 as ccreditsales, convert(numeric(18,8),sum(lphbillamount)) as localpurchase,                          
--convert(numeric(18,8),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,                           
--convert(numeric(18,8),sum(lphbillamount*lphexchangerate)) as clocalpurchase                          
----RefNo-2 start -------------------      
--,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                                 
--0.0 as cPdChequeSales      
----RefNo-2 end -------------------                                
--,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
--from loslocalpurchaseheader lh,adepartmentmaster d where                          
--lh.lphDepartmentID=d.departmentid  and lh.lphcashpurchase=1  and lphcancelled=0                          
--group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate) summary                           
--group by companyid ,departmentid, shopid, billdate

select lh.lphcompanyid,lh.lphdepartmentid,lh.lphshopid,lh.lphbilldate, 0.0 cashsales,                           
0.0 dcashsales, 0.0 ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard,                          
0.0 as debitcard, 0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts,              
0.0 as creceipts, 0.0 as payments, 0.0 as dpayments, 0.0 as cpayments, 0.0 as creditsales,                           
0.0 as dcreditsales, 0.0 as ccreditsales,
--convert(numeric(18,8),sum(lphbillamount)) as localpurchase1,                          
--convert(numeric(18,8),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,                           
--convert(numeric(18,8),sum(lphbillamount*lphexchangerate)) as clocalpurchase                          
convert(numeric(18,8),sum(lphbillamount-isnull(ld.lpdItemTaxAmount,0))) as localpurchase,   
convert(numeric(18,8),sum(lphbillamount-isnull(ld.lpdItemTaxAmount,0))* lphdepexrate) as dlocalpurchase,                           
convert(numeric(18,8),sum(lphbillamount-isnull(ld.lpdItemTaxAmount,0))*lphexchangerate) as clocalpurchase,
-- RefNo-5  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                            
-- RefNo-5  
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
--RefNo-2 ends -------------------
,convert(numeric(18,8),sum(isnull(ld.lpdItemTaxAmount,0))) as GSTAmount,
convert(numeric(18,8),sum(isnull(ld.lpdItemTaxAmount,0))*lphdepexrate) as dGSTAmount,
convert(numeric(18,8),sum(isnull(ld.lpdItemTaxAmount,0))*lphexchangerate) as cGSTAmount
from loslocalpurchaseheader lh,adepartmentmaster d,
(select lpdShopID,lpdBillID , SUM(isnull(lpdItemTaxAmount,0))lpdItemTaxAmount 
 from loslocalpurchaseDetail group by lpdShopID,lpdBillID)ld
where                          
lh.lphDepartmentID=d.departmentid and lh.lphcashpurchase=1  and lphcancelled=0 
and lh.lphBillID = ld.lpdBillID and lh.lphShopID = ld.lpdShopID                            
group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate
,lphdepexrate,lphexchangerate
) summary                           
group by companyid ,departmentid, shopid, billdate 


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Update Description New Report-> Sales and Collection Summary GST Separately from bijesh on 27.09.2012 from bijesh
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwshopservicesalesWithOutGST')
   DROP view dbo.vwshopservicesalesWithOutGST
GO
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 --Last Modified on  : 19/10/2004    
--Modified by  : Aneesh  
------------------------------------------------------------------------------------------           
-- Modified by  : Bijesh.B  
-- Date         : 19/08/2011  
-- RefNo        : RefNo-5   
-- Ticket Id    : JSZ-828136 (SHEESHA)  
-- Description  : Need UserWise selection for Cash Denomination interface  
--              : siUserID column included  
------------------------------------------------------------------------------------------           
--RefNo        : Newly created view (copy of vwshopservicesales)  
--Modified by  : Bijesh.B  
--Date         : 13/03/2012,11/04/2012 (addes sum() in GST Amount)  
--Ticket id    : JDJ-400367 (Sonee)  
--comments     : Need to show GST separately  
----------------------------------------------------------------------------------------------     
--Modified by  : Bijesh.B  
--Date         : 09/07/2-12 
--Ticket id    : JDJ-400367 (Sonee)  
--comments     : Removde sum() in GST Amount, corrected sicamount and sidamount
----------------------------------------------------------------------------------------------     
    
create View vwshopservicesalesWithOutGST As  
    Select sicompanyid, sishopid, aiinvoicedate As siinvoicedate, aiinvoiceno, siinvoiceid,     
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then     
        ((Sum(siServiceQty * siAmount)) -IsNull(aiDiscount,0))   
    Else     
        (Sum((siServiceQty * siAmount) + siClearingCommAmt)) -IsNull(aiDiscount,0)  End  
        As siamount,

    Sum(aiSettledamount) Settledamount ,     
  
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then     
        Sum( ((siServiceQty * siAmount)- IsNull(aiDiscount,0)) * aiexchangerate)
    Else     
        Sum( (((siServiceQty * siAmount) + siClearingCommAmt) 
              -IsNull(aiDiscount,0))* aiexchangerate) End  As sicamount,     
       
    Case Convert(Int, IsNull(aiCashPaidByShop,0)) When 0 Then     
        Sum(((siServiceQty * siAmount) -IsNull(aiDiscount,0))* aidepexrate) 
    Else     
        Sum((((siServiceQty * siAmount) + isnull(siClearingCommAmt,0)) 
			 -IsNull(aiDiscount,0))* aidepexrate)
			 End As sidamount       
		
    ,ISNULL(siUserID,0) as UserID  
    ,(isnull(aiTaxAmount,0)) GSTAmount  
    ,(isnull(aiTaxAmount,0) * aidepexrate) as dGSTAmount  
    ,(isnull(aiTaxAmount,0) * aiexchangerate) as cGSTAmount    
    From LOsServiceInvoiceDetails, LOsAccountsInvoiceHeader  
    Where aicancelled=0 And aiproforma=0 And aiinvoiceid = siinvoiceid And aishopid = sishopid   
    Group By sicompanyid, sishopid, aiinvoicedate,   
    siinvoiceid, aiinvoiceno, aiexchangerate,  aidepexrate,aiDiscount,isnull(aiTaxAmount,0),  
    Convert(Int, IsNull(aiCashPaidByShop,0)),ISNULL(siUserID,0)  
    
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Update Description 	New Report-> Sales and Collection Summary GST Separately from bijesh on 27.09.2012 from bijesh
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwCAshSalesGSTSeparately')
   DROP view dbo.vwCAshSalesGSTSeparately
GO
  

-- Modified On          : 21/06/2004      
-- Modified by          : Hariharan R, Vekitesh , Aneesh      
-- Comments             : added Goods return Case      
--   : added utility bills And corrected amount column for dep in room billing      
--   : Other charges given in Group Byclause to avoid doubling in Invoice queries      
--   : corrrected order of goods return note amount selecitOn      
--   : Shop debit credit note query added   
-------------------------------------------------------------------------------------------  
--Modified by           : Bijesh.B as on 07/06/2011  
--            : RefNo-1  
--Comments              : Since Post Dated Cheque (Fully/Partially) option was included   
--        in POS(Sonee) interface,the difference between 'BILL AMOUNT' and   
--        PD Cheque Amount is the actual Cash Sales      
--Backup                : vwCAshSalesAsOn07062011   
------------------------------------------------------------------------------------------           
-- Modified by : Bijesh.B  
-- Date        : 17/06/2011, 04/07/2011  
-- RefNo       : RefNo-2   
-- Comments    : PD Cheque feature added      
------------------------------------------------------------------------------------------           
-- Modified by : Bijesh.B  
-- Date        : 03/07/2011  
-- RefNo       : RefNo-3   
-- Comments    : Removed the link from ahqPostDatedChequeDetails  
--               Need to show 'pd cheque amount' even if it is not registered     
------------------------------------------------------------------------------------------           
-- Modified by : Bijesh.B  
-- Date        : 28/07/2011  
-- RefNo       : RefNo-4   
-- Comments    : Bugsheet - Spl Invoice amount is wrongly updated in cash sales,  
------------------------------------------------------------------------------------------           
-- RefNo        : RefNo-5   
-- Modified by  : Bijesh.B  
-- Date         : 19/08/2011  
-- Ticket Id    : JSZ-828136 (SHEESHA)  
-- Description  : Need UserWise selection for Cash Denomination interface  
--              : UserID column included in all query   
------------------------------------------------------------------------------------------  
-- RefNo        : RefNo-6   
-- Modified by  : AADYAKUMAR D V
-- Date         : 21/01/2012  
-- Description  : Added F&B part 
------------------------------------------------------------------------------------------          
----------------------------------------------------------------------------------------------       
--RefNo        : New View (copy of vwCAshSales)
--Created by   : Bijesh.B 
--Date         : 11/04/2012
--Ticket id    : JDJ-400367 
--Comments     : new reports (rtdailysalescollectionshopwiseGSTSeparately,
--				 rptdailysalescollectiondepwiseGSTSeparately)    for sonee - GST separation)
----------------------------------------------------------------------------------------------       
--RefNo         : RefNo-7
--Modified by   : Bijesh.B 
--Date          : 13/07/2012
--Ticket id     : JDJ-400367 
--Desc          : correct values
----------------------------------------------------------------------------------------------       
--RefNo         : RefNo-8
--Modified by   : Bijesh.B 
--Date          : 16/07/2012
--Ticket id     : JDJ-400367 
--Desc          : correctd values
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-9
--Date         : 03/08/2012  
--Comments     : Corrected Other Charges Service Tax in Credit Invoice
----------------------------------------------------------------------------------------------       
--Modified by  : BIJESH.B   
--RefNo        : RefNo-11
--Date         : 27/09/2012  
--Comments     : Corrected values incase of PD Cheque enabled cash sales is exchanged
----------------------------------------------------------------------------------------------       

create View vwCAshSalesGSTSeparately As    

	Select poshcompanyid As companyid, poshshopid As shopid, poshbilldate As billdate,       
		poshcAshaccid As accountid, 
		convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) amount, 
		convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) damount,
		convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) camount,
		1 As cAsh, 'p' As transtype, poshdepartmentid departmentid ,0 as PdChqCancelled  
		,ISNULL(poshUserId,0) as UserID   
		,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,
		convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,
		convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount
	From  
		losposheader ph,losposdetail pd   
	Where       
		ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0       
		and isnull(ph.PosPostDate,0)<>1  
	Group By 
		poshcompanyid , poshshopid , poshbilldate ,poshbillid, poshcAshaccid ,       
		poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate,ISNULL(poshUserId,0)      

UNION ALL  

    --RefNo-1  
    --FULL PD CHEQUE 
    Select poshcompanyid As companyid, ph.poshshopid As shopid, poshbilldate As billdate,       
		poshcAshaccid As accountid,  
		--Convert(numeric(18,8),(ph.poshBillAmount - PDCheque.PosBankAmount)) as amount,   
		--Convert(numeric(18,8),(ph.poshBillAmount - PDCheque.PosBankAmount) * poshdepexrate)  As damount,      
		--Convert(numeric(18,8), (ph.poshBillAmount - PDCheque.PosBankAmount) * poshexchangerate) As camount,    

		-- convert(numeric(18,8),sum(posdunitprice)-pdCheque.PosBankAmount) amount,   
		-- convert(numeric(18,8),sum(posdunitprice * poshdepexrate)-pdCheque.PosBankAmount) damount,   
		-- convert(numeric(18,8),sum(posdunitprice * poshexchangerate)-pdCheque.PosBankAmount) camount,  
		convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) amount, 
		convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) damount,
		convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) camount,
		0 As cAsh, 'PD CHEQUE' As transtype, poshdepartmentid departmentid, 0 as PdChqCancelled      
		,ISNULL(poshUserId,0) as UserID  
		,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,
		convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,
		convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount
	 From  
		losposheader ph,losposdetail pd,losPosChequeDetails PDCheque  
	Where       
		ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0       
		and isnull(ph.PosPostDate,0)=1   
		and PDCheque.PoshBillID = ph.poshBillID and PDCheque.PoshShopID = ph.poshShopID  
	Group By 
		poshcompanyid , ph.poshshopid , poshbilldate ,ph.poshbillid, poshcAshaccid ,       
		poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate ,  
		PDCheque.PosBankAmount,ISNULL(poshUserId,0)  

UniOn All      

	Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,       
		convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0)))) amount,
		convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) damount,
		convert(numeric(18,8),sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) camount,
		1,'e'  As transtype, sehdepartmentid departmentid,0 as PdChqCancelled  
		,ISNULL(sehUserID,0) as UserID           
		,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount
		,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
		convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount
	From  
		losposexchangeheader ph, losposexchangedetail pd       
	Where 
		ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid And       
		sehcancelled=0 And sedbillorexchange ='E'     
	Group By 
		sehcompanyid,sehshopid, sehexchangedate, sehexchangeid,    
		sehcAshaccid, sehdepartmentid, sehdepexrate, sehexchangerate,ISNULL(sehUserID,0)       

Union All      
   
--RefNo-4 start   
-- commented below   
/*  
Select       
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,       
 COnvert(numeric(18,8),Sum( vw.idunitprice ))  As amount,      
 COnvert(numeric(18,8),Sum( vw.idunitprice) * ihdepexrate)  As damount,      
 COnvert(numeric(18,8),Sum( vw.idunitprice) * ihexchangerate)  As camount,      
 1, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled      
From       
 losspecialinvoiceheader ih, vwShopSplInvItemAmount vw       
Where       
 ih.ihshopid = vw.idshopid And ih.ihinvoiceid = vw.idinvoiceid And       
 ihcancelled=0 And ihcAshinvoice =1 And ih.ihproforma =0 And ihtransfinIshed=1      
Group By    
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
 ihdepexrate, ihexchangerate  
  
UniOn All      
  
--direct invoice      
Select       
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,       
 COnvert(numeric(18,8),Sum(idunitprice) ) As amount,       
 COnvert(numeric(18,8),Sum(idunitprice) * ihdepexrate) As damount,       
 COnvert(numeric(18,8),Sum(idunitprice) * ihexchangerate) As camount,       
 0 ihcAshinvoice, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled      
From       
 losspecialinvoiceheader ih, vwShopSplInvItemAmount invd       
Where       
 ih.ihshopid = invd. idshopid And ih.ihinvoiceid = invd.idinvoiceid And       
 ihcancelled=0 And ihcAshinvoice =0 And ih.ihproforma =0 And ihTransfinIshed =1      
Group By    
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,       
 ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate   
*/  
   
-- special Invoice (cash)    
select ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,             
	--convert(numeric(18,8),sum(idUnitPrice)) amount,  
	--convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) damount,  
	--convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) camount, 
	convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) amount,
	convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) damount,
	convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) camount, 
	1, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled     
	,ISNULL(ihUserId,0) as UserID  
	,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
	convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                   
	losspecialinvoicedetail, losspecialinvoiceheader                                   
where          
	ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                
	IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                  
	and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0                              
Group By    
	ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
	ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0)  
                               
union all           
	  
	-- special invoice - return before despatch         
	select ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,       
		--convert(numeric(18,8),-sum(idUnitPrice)) amount,  
		--convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) damount,  
		--convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) camount,                                   
		convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
		convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) damount,    
		convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) camount,     
		1, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled     
		,ISNULL(ihUserId,0) as UserID  
		,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
		,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
		convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
	from                                   
		losspecialinvoicedetail,losspecialinvoiceheader                                  
	where   
		ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                   
		idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1   
		and ihNoofOCDetails<>0                              
	Group By    
		ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
		ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0)  
                                      
UNION ALL                                  
                               
	-- Special invoice return  - after desp                                
	select ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,  
		--convert(numeric(18,8),-sum(idUnitPrice)) amount,  
		--convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) damount,   
		--convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) camount,                                   
		convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
		convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) damount,    
		convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) camount,   
		1, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled   
		,ISNULL(ihUserId,0) as UserID  
		,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
		,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
		convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
	from                                   
		losspecialinvoicedetail,losspecialinvoiceheader                                  
	where            
		ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                   
		idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1                                 
	Group By    
		ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
		ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0)   
  
-- special Invoice (credit)  
UNION ALL  
 
select ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,             
	--convert(numeric(18,8),sum(idUnitPrice)) amount,  
	--convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) damount,  
	--convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) camount,
	convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
	convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) damount,    
	convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) camount,  
	0, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled     
	,ISNULL(ihUserId,0) as UserID  
	,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
	convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                   
	losspecialinvoicedetail, losspecialinvoiceheader                                   
where                                   
	ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                
	IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                  
	and IhTransFinished = 1 And ihcAshinvoice<>1 and ihNoofOCDetails=0                              
Group By    
	ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
	ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0)  
                               
UNION ALL                                  
  
-- special invoice - return before despatch                      
select ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,       
	--convert(numeric(18,8),-sum(idUnitPrice)) amount,  
	--convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) damount,  
	--convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) camount,                                   
	 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
	 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) damount,    
	 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) camount,   
	0, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled     
	 ,ISNULL(ihUserId,0) as UserID  
	 ,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
	 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                   
	losspecialinvoicedetail,losspecialinvoiceheader                                  
where        
	ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                   
	idratetype = 0 and ihproforma = 0 And ihcAshinvoice<>1 and ihTransFinished = 1   
	and ihNoofOCDetails<>0                              
Group By    
	ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
	ihdepexrate, ihexchangerate ,ISNULL(ihUserId,0)   
                                      
union all                                  
                               
-- Special invoice return  - after desp                                
select                                   
	 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,  
	 --convert(numeric(18,8),-sum(idUnitPrice)) amount,  
	 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) damount,   
	 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) camount,                                   
	 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
	 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)damount,    
	 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)camount,     
	 0, 'd' As transtype, ihdepartmentid departmentid  ,0 as PdChqCancelled   
	,ISNULL(ihUserId,0) as UserID  
	,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
	 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                   
	 losspecialinvoicedetail,losspecialinvoiceheader                                  
where            
	 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                   
	 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice<>1                                 
Group By    
	ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
	ihdepexrate, ihexchangerate,ISNULL(ihUserId,0)  
--RefNo-4 ends   
 
UniOn All      
--RefNo-11 start   commented below and added   
   -- Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,       
   --convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) amount,
   --convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) damount,
   --convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) camount,

   --1, 'e' As transtype, sehdepartmentid  departmentid ,0 as PdChqCancelled    
   --,ISNULL(sehUserID,0) as UserID
   --,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount
   --,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
   -- convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount

   -- From   losposexchangeheader ph, losposexchangedetail pd      
   -- Where ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid       
   -- And sehcancelled=0 And sedbillorexchange ='B' And sedexchangeqty > 0      
   -- Group By sehcompanyid, sehshopid, sehexchangedate, sehexchangeid, sehcAshaccid,       
   -- sehdepartmentid, sehdepexrate, sehexchangerate,ISNULL(sehUserID,0)  

Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,       
	convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) amount,
	convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) damount,
	convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) camount,
	1, 'e' As transtype, sehdepartmentid  departmentid ,0 as PdChqCancelled    
	,ISNULL(sehUserID,0) as UserID
	,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
	convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount
From   
	losposexchangeheader ph, losposexchangedetail pd,LOsPosHeader posh        
Where ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid       
	And sehcancelled=0 And sedbillorexchange ='B' And sedexchangeqty > 0      
	and posh.poshBillID=ph.sehBillID  and posh.poshShopID= ph.sehShopID 
	and  isnull(posh.PosPostDate,0)=0
Group By 
	sehcompanyid, sehshopid, sehexchangedate, sehexchangeid, sehcAshaccid,       
	sehdepartmentid, sehdepexrate, sehexchangerate,ISNULL(sehUserID,0)  

union all  --pd cheque

Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,       
	convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0)))) amount,
	convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehdepexrate) damount,
	convert(numeric(18,8),-sum((sedunitprice-isnull(sedItemTaxAmount,0))) * sehexchangerate) camount,
	0, 'PD CHEQUE' As transtype, sehdepartmentid  departmentid ,0 as PdChqCancelled    
	,ISNULL(sehUserID,0) as UserID
	,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
	convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount
From   
	losposexchangeheader ph, losposexchangedetail pd,LOsPosHeader posh        
Where ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid       
	And sehcancelled=0 And sedbillorexchange ='B' And sedexchangeqty > 0      
	and posh.poshBillID=ph.sehBillID  and posh.poshShopID= ph.sehShopID 
	and  isnull(posh.PosPostDate,0)=1
Group By 
	sehcompanyid, sehshopid, sehexchangedate, sehexchangeid, sehcAshaccid,       
	sehdepartmentid, sehdepexrate, sehexchangerate,ISNULL(sehUserID,0)  
      
--RefNo-11 ends
UniOn All      

Select ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,       
	--   Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	--	(Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0))     
	--		Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))  End Amount,       
	--Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	--	(Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0)) * ihdepexrate    
	--	Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))* ihdepexrate  End DAmount,       
	--   Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	--    (Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0)) * ihExchangeRate     
	--   Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))* ihExchangeRate End cAmount,     

	Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
		(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0))     
			Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))  End Amount,       
	Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
		(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0)) * ihdepexrate    
		Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))* ihdepexrate  End DAmount,       
	Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
		(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0)) * ihExchangeRate     
	Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))* ihExchangeRate End cAmount,     

	1,'c' As transtype, ih.ihdepartmentid  departmentid ,0 as PdChqCancelled    
	,ISNULL(ihuserid,0) as UserID    
	,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,
	convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount

From  losinvoiceheader ih 
	Left Outer Join losinvoicedetail invd On ih.ihshopid = invd.idshopid      
			And ih.ihinvoiceid = invd.idinvoiceid  
	Left Outer Join (Select ioShopID,ioInvoiceID,Sum(ioAmount) ioAmount From losInvoiceOC       
					 Group By   ioShopID,ioInvoiceID) ocd  
	On ihshopid= ocd.ioShopid And ihinvoiceid=ocd.ioInvoiceID, Ashops s   
	Where 
		ihcancelled=0 And ihcAshinvoice = 1 And ih.ihproforma =0 And ih.ihtype='I'      
		And ihshopid = s.shopid And ihcompanyid = s.COmpanyid      
	Group By 
		ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid,     
		ihdepartmentid,  ihdepexrate, ihexchangerate, ocd.ioAmount, s.futurevarchar,  
		ih.ihdutypaidby,ISNULL(ihuserid,0)
    
UniOn All      
      
Select       
	vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,       
	--RefNo-10 start commented and added
	--COnvert(numeric(18,8),(vws.siamount )) As amount,       
	--COnvert(numeric(18,8),(vws.siamount) * aidepexrate) As damount,      
	--COnvert(numeric(18,8),(vws.siamount) * aiexchangerate) As camount,      
	convert(numeric(18,8),(vws.siamount))as amount,   
	convert(numeric(18,8),(vws.sidamount))as  damount,
	convert(numeric(18,8),(vws.sicamount))as camount, 
	--RefNo-10 ends
	lah.aicAshinvoice , 's' As transtype, aidepartmentid departmentid ,0 as PdChqCancelled      
	,ISNULL(vws.UserID,0) as UserID   
	, (vws.GSTAmount)as GSTAmount
	, (vws.dGSTAmount)as dGSTAmount
	, (vws.cGSTAmount)as cGSTAmount
From       
	vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah, vwshops s      
Where       
	s.shopid = aIshopid And aiinvoiceid=siinvoiceid And aicancelled=0 And       
	aiproforma=0 And aIshopid = sIshopid And lah.aicAshinvoice =1   
      
UniOn All      

--hq serivce invoice dOne for shop      
Select       
 ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,       
 --COnvert(numeric(18,8),Sum(serviceqty * amount) ),      
 --COnvert(numeric(18,8),Sum(serviceqty * amount) *depexrate),      
 --COnvert(numeric(18,8),Sum(serviceqty * amount) *exchangerate),      

COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  amount,             
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)damount,       
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)camount,       
 
 1 ,'hs', ai.departmentid  departmentid  ,0 as PdChqCancelled      
 ,ISNULL(ser.UserID,0) as UserID 
  ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount 
 ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,
  convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount

From       
 accountsinvoiceheader ai, serviceinvoicedetails ser       
Where       
 ai.invoiceid = ser.invoiceid And ai.companyid =       
 ser.companyid And ai.cAshinvoice = 1 And ai.cancelled = 0 And ai.proforma = 0       
Group By     
 ai.companyid, ai.invoicedate,ai.invoiceid,ai.exchangerate,ai.bankcAshid,       
 ai.departmentid, depexrate, exchangerate ,ISNULL(ser.UserID,0)  
      
UniOn All      
      
-- hari included From credit sales to correct the daily sales Summary report      

--RefNo-9 start commented and added
--Select       
-- ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,       
-- Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
-- (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0)) -- +Isnull(Sum(invd.idcdcustcur),0)      
-- Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))  End Amount,       
-- Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
-- (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0)) * ihdepexrate --  +Isnull(Sum(invd.idcdcustcur),0)      
-- Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))* ihdepexrate  End DAmount,       
-- Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
-- (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0)) * ihExchangeRate -- +Isnull(Sum(invd.idcdcustcur),0)      
-- Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))* ihExchangeRate End cAmount,       
-- 0 ihcAshinvoice, 'c' As transtype, ih.ihdepartmentid  departmentid ,0 as PdChqCancelled    
--,ISNULL(ihuserid,0) as UserID  
--,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
--,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,
--convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount
 
--From       
-- losinvoiceheader ih       
-- Left Outer Join losinvoicedetail invd       
-- On ih.ihshopid = invd.idshopid And ih.ihinvoiceid = invd.idinvoiceid      
-- Left Outer Join       
-- (Select      
--  ioShopID,ioInvoiceID,Sum(ioAmount) ioAmount      
-- From      
--  losInvoiceOC       
-- Group By     
--  ioShopID,ioInvoiceID) ocd       
-- On ihshopid= ocd.ioShopid And ihinvoiceid=ocd.ioInvoiceID, Ashops s  
--Where       
-- ihcancelled=0 And ihcAshinvoice =0 And ih.ihproforma =0 And ih.ihtype='I'      
-- And ihshopid = s.shopid And ihcompanyid = s.COmpanyid      
--Group By   
-- ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,       
-- ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate, ocd.ioAmount,       
-- s.futurevarchar, ih.ihdutypaidby,ISNULL(ihuserid,0)           

 --credit invoice(Excluding Other charges)
Select       
 ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,       
 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) 
 Else 
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))  
 End Amount,       
 
 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihdepexrate 
 Else
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))* ihdepexrate  
 End DAmount,       
 
 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihExchangeRate
 Else
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))* ihExchangeRate 
 End cAmount, 
       
 0 ihcAshinvoice, 'c' As transtype, ih.ihdepartmentid  departmentid ,0 as PdChqCancelled    
,ISNULL(ihuserid,0) as UserID  
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount
 
From       
 losinvoiceheader ih       
 Left Outer Join losinvoicedetail invd       
 On ih.ihshopid = invd.idshopid And ih.ihinvoiceid = invd.idinvoiceid      
 --Left Outer Join       
 --(Select      
 -- ioShopID,ioInvoiceID,Sum(ioAmount) ioAmount      
 --From      
 -- losInvoiceOC       
 --Group By     
 -- ioShopID,ioInvoiceID) ocd       
 --On ihshopid= ocd.ioShopid And ihinvoiceid=ocd.ioInvoiceID
 ,Ashops s  
Where       
 ihcancelled=0 And ihcAshinvoice =0 And ih.ihproforma =0 And ih.ihtype='I'      
 And ihshopid = s.shopid And ihcompanyid = s.COmpanyid      
Group By   
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,       
 ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate,
 s.futurevarchar, ih.ihdutypaidby,ISNULL(ihuserid,0)           

union all

 --Credit Invoice (Other Charges only)
Select       
 ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,       

 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	 convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))              
 Else 
	convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))              
 End Amount,       

Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) 
Else 
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) 
End DAmount,       

Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate) 
Else
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate)
End cAmount,       

0 ihcAshinvoice, 'c' As transtype, ih.ihdepartmentid  departmentid ,0 as PdChqCancelled    
,ISNULL(ihuserid,0) as UserID  
,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihdepexrate)dGSTAmount
,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihexchangerate)cGSTAmount

from losinvoiceheader  ih                  
	left outer join losInvoiceOC ocd  on ihshopid= ocd.ioShopid 
		and ihinvoiceid=ocd.ioInvoiceID         
	,ashops s, adepartmentmaster d                   
where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
group by  
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,       
 ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate,
 s.futurevarchar, ih.ihdutypaidby,ISNULL(ihuserid,0) 

--RefNo-9 ends
      
UniOn All      
      
--serviceinvoice      
Select       
 vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,       
 --RefNo-10 start
 --COnvert(numeric(18,8),vws.siamount) As amount,       
 --COnvert(numeric(18,8),vws.siamount * aidepexrate) As damount,       
 --COnvert(numeric(18,8),vws.siamount * aiexchangerate) As camount,
	convert(numeric(18,8),(vws.siamount))as  amount,   
	convert(numeric(18,8),(vws.sidamount))as damount,
	convert(numeric(18,8),(vws.sicamount))as camount, 
 --RefNo-10 ends
 lah.aicAshinvoice,'s' As transtype, lah.aidepartmentid  departmentid ,0 as PdChqCancelled   
,ISNULL(vws.UserID,0) as UserID   
,(vws.GSTAmount)as GSTAmount
,(vws.dGSTAmount)as dGSTAmount
,(vws.cGSTAmount)as cGSTAmount
From       
 vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah      
Where       
 aiinvoiceid=siinvoiceid And aicancelled=0 And aiproforma=0 And aIshopid = sIshopid      
 And lah.aicAshinvoice=0      
      
-- hari included     
 UniOn All      
--hq serivce invoice dOne for shop      
Select       
 ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,       
 --COnvert(numeric(18,8),Sum(serviceqty * amount) ),       
 --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate),      
 --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate),   
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  amount,             
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)damount,       
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)camount,       
0 ,'hs',ai.departmentid  departmentid   ,0 as PdChqCancelled     
,ISNULL(ser.UserID,0) as UserID   
,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount 
,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,
convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount
From       
 accountsinvoiceheader ai, serviceinvoicedetails ser       
Where       
 ai.invoiceid = ser.invoiceid And ai.companyid =       
 ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0       
Group By    
 ai.companyid, ai.invoicedate, ai.invoiceid, ai.exchangerate,ai.bankcAshid,       
 ai.departmentid, depexrate, exchangerate,ISNULL(ser.UserID,0)   
      
-- hari included for service booking advances      
UniOn All      
      
Select       
 serbookhcompanyid, serbookhshopid, serbookadvancedate, serbookhcAshacc,       
 COnvert(numeric(18,8), serbookadvanceamount) ,      
 COnvert(numeric(18,8), serbookadvanceamount * serbookhdepexrate),      
 COnvert(numeric(18,8), serbookadvanceamount * serbookhcmpexrate), 1  ,'sb',       
 serbookhdepartmentid ,0 as PdChqCancelled   
,ISNULL(serbookhUserid,0) as UserID 
,0,0,0  
From LOsServiceBookingHeader      
       
Where       
 serbookhinpcancelled=0       
        And serbookadvanceamount>0      
      
-- hari included for service booking invoices which are cAsh invoices      
UniOn All      
      
Select       
 serinvhcompanyid, serinvhshopid, serinvhdate, serinvhcAshacc,       
 --COnvert(numeric(18,8), serinvhamount) ,       
 --COnvert(numeric(18,8), serinvhamount * seinvhdepexrate) ,       
 --COnvert(numeric(18,8), serinvhamount * serinvhcmpexrate),
 COnvert(numeric(18,8),serinvhamount-isnull(serinvhTaxamount,0)) ,       
 COnvert(numeric(18,8),(serinvhamount-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,       
 COnvert(numeric(18,8),(serinvhamount-isnull(serinvhTaxamount,0)) * serinvhcmpexrate),
 1 , 'sbi',       
 serinvhdepartmentid  ,0 as PdChqCancelled   
,ISNULL(serinvhuserid,0) as UserID   
,convert(numeric(18,8),(isnull(serinvhTaxamount,0)))GSTAmount
,convert(numeric(18,8),(isnull(serinvhTaxamount,0))* seinvhdepexrate)dGSTAmount,
 convert(numeric(18,8),(isnull(serinvhTaxamount,0))* serinvhcmpexrate)cGSTAmount
From       
 losserviceinvheader       
Where       
 serinvhcancelled = 0   And       
 serinvhamount>0 And serinvhcAshacc Is Not Null      
      
-- hari included for service booking invoices which are credit invoices      
UniOn All      
      
Select       
 serinvhcompanyid, serinvhshopid, serinvhdate, serinvhcAshacc,       
 --COnvert(numeric(18,8), serinvhamount),
 --COnvert(numeric(18,8), serinvhamount*seinvhdepexrate),      
 --COnvert(numeric(18,8), serinvhamount * serinvhcmpexrate), 
 COnvert(numeric(18,8),serinvhamount-isnull(serinvhTaxamount,0)) ,       
 COnvert(numeric(18,8),(serinvhamount-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,       
 COnvert(numeric(18,8),(serinvhamount-isnull(serinvhTaxamount,0)) * serinvhcmpexrate),
 0 , 'sbi',       
 serinvhdepartmentid  ,0 as PdChqCancelled   
,ISNULL(serinvhuserid,0) as UserID   
,convert(numeric(18,8),(isnull(serinvhTaxamount,0)))GSTAmount
,convert(numeric(18,8),(isnull(serinvhTaxamount,0))* seinvhdepexrate)dGSTAmount,
 convert(numeric(18,8),(isnull(serinvhTaxamount,0))* serinvhcmpexrate)cGSTAmount
From       
 losserviceinvheader       
Where       
 serinvhcancelled = 0 And       
 serinvhamount>0 And serinvhcAshacc Is null      
      
UniOn All      
      
Select  abh.abhcompanyid, abh.abhshopid,abhBillDate, abh.abhCAshAccId,       
COnvert(numeric(18,8), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,       
COnvert(numeric(18,8), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,       
COnvert(numeric(18,8), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,       
0, 'RBI' type , abh.abhdepartmentid departmentid  ,0 as PdChqCancelled   
,ISNULL(abhUserID,0) as UserID 
,0,0,0  
From       
losApartmentBillHeader abh Where abh.abhCancelled = 0 And abh.abhCAshAccId Is null      
      
UniOn All      
      
Select  abh.abhcompanyid, abh.abhshopid,abhBillDate, abh.abhCAshAccId,       
COnvert(numeric(18,8), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,       
COnvert(numeric(18,8), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,       
COnvert(numeric(18,8), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,       
1, 'RBI' type , abh.abhdepartmentid departmentid ,0 as PdChqCancelled   
,ISNULL(abhUserID,0) as UserID   
,0,0,0
From losApartmentBillHeader abh Where abh.abhCancelled = 0 And abh.abhCAshAccId Is Not Null      
  
UniOn All      
-- UTILITY BILL CREDIT INVOICES       
Select       
 tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhBillDate, tbh.tbhBankCAshID,       
 COnvert(numeric(18,8), Isnull(tbh.tbhAmount,0)) Amount,       
 COnvert(numeric(18,8), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,       
 COnvert(numeric(18,8), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,       
 0, 'UTB' type , tbh.tbhdepartmentid departmentid  ,0 as PdChqCancelled   
,ISNULL(tbhUserID,0) as UserID   
,0,0,0
From       
 losTenantServiceBillHeader tbh, acustomermAster c      
Where       
 tbh.tbhCustomerID=c.customerID And tbh.tbhBankCAshID Is null And      
 tbh.tbhCancelled=0       
      
    UniOn All      
      
-- UTILITY BILL CAsH INVOICES      
    Select tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhBillDate, tbh.tbhBankCAshID,       
    COnvert(numeric(18,8), Isnull(tbh.tbhAmount,0)) Amount,       
    COnvert(numeric(18,8), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,       
    COnvert(numeric(18,8), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,       
    1, 'UTB' type , tbh.tbhdepartmentid departmentid,0 as PdChqCancelled          
    ,ISNULL(tbhUserID,0) as UserID   
    ,0,0,0
    From losTenantServiceBillHeader tbh, acustomermAster c      
    Where  tbh.tbhCustomerID=c.customerID And tbh.tbhBankCAshID Is Not Null And      
    tbh.tbhCancelled=0     
      
    UniOn All      
      
    Select GrnCompanyID, grnhshopid, grnhGoodsReturnNoteDate, grnhCustomerId,       
    -- -COnvert(numeric(18,8),Sum(grndunitprice))  amount,       
    -- -COnvert(numeric(18,8),Sum(grndunitprice) * grnhdepExRate)  damount,      
    -- -COnvert(numeric(18,8),Sum(grndunitprice) * grnhExchangeRate)  camount, 
   -convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) amount,                 
   -convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhdepexRate) damount,                 
   -convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhExchangeRate) camount, 
    0, 'c' As transtype, Grnhdepartmentid  departmentid  ,0 as PdChqCancelled   
    ,ISNULL(grnUserID,0) as UserID   
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,
    -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount
    From losGoodsReturnNoteHeader ih, losGoodsReturnNoteDetail invd       
 Where ih.GrnhShopid = invd.grndshopid And ih.GrnhGoodsreturnnoteID = invd.GrndreturnnoteID      
    And grnhCancel = 0  Group By grncompanyid, grnhshopid, grnhGoodsReturnNoteDate,       
    GrnhGoodsreturnnoteID, grnhCustomerID, grnhdepartmentid, grnhdepExRate, grnhExchangeRate  
    ,ISNULL(grnUserID,0)   
              
    UniOn All    
    --Shop debit credit notes and handling debit notes which are debit to the  
    -- customer and hence act as invoices to be settled        
    Select  losdcnCompanyID, losdcnshopid,losdcndate, losdcncustomerid,    
    COnvert(numeric(18,8),Sum(losDCNAmount))  amount,       
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  damount,      
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  camount,        
    0, 'sdcn' As type , losdcndepartmentid ,0 as PdChqCancelled   
    ,ISNULL(losDCNUserID,0) as UserID   
    ,0,0,0
    From Ashops s, acustomermAster c,     
    losdebitcreditnote Where  s.shopid = losdcnshopid And s.accountable Is Not Null     
    And c.customerid = losdcncustomerid And losdcncustomerid Is Not Null And       
    losdcncancelled =0 And losdcndebit =1  Group By losdcnCompanyID,losdcnshopid,    
    losdcndate, losdcncustomerid,losdepexrate, losexchangerate,losdcndepartmentid   
    ,ISNULL(losDCNUserID,0)  
    
--UNION ALL   
----RefNo-1  
---- PD Cheque only  
--SELECT       
-- poshCompanyID As companyid,PH.poshshopid As shopid, poshbilldate As billdate,       
--    ISNULL(poshChequeAccID,0) As accountid,   
--    Convert(numeric(18,8), CHQ.PosBankAmount)  As amount,      
--    Convert(numeric(18,8), CHQ.PosBankAmount * poshdepexrate)  As damount,   
--    Convert(numeric(18,8), CHQ.PosBankAmount * poshexchangerate) As camount,       
--    0,'PD CHEQUE' As transtype, poshdepartmentid departmentid,0 as PdChqCancelled   
--  ,ISNULL(poshUserId,0) as UserID   
-- FROM   
-- losPosChequeDetails CHQ,LOsPosHeader PH  
-- --, ahqPostDatedChequeDetails PdChqDet  --RefNo-3  
-- WHERE   
--    PH.poshcancelled <> 1 AND --RefNo-2  
-- PH.poshBillID = CHQ.PoshBillID  AND isnull(PH.PosPostDate,0)=1   
-- AND PH.poshShopID = CHQ.PoshShopID  
-- --and PdChqDet.PoshBillID = ph.poshBillID  --RefNo-3  
-- --AND isnull(PdChqDet.Cancel,0)=0          --RefNo-3  
--    Group By poshcompanyid , PH.poshshopid , poshbilldate ,PH.poshbillid, poshcAshaccid ,       
--    poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate,poshChequeAccID,  
--    CHQ.PosBankAmount,ISNULL(poshUserId,0)
--RefNo-6-----------------------------------------------start-----------------------------------------------------------------
   --UNION ALL   
    
   -- Select poshcompanyid As companyid, poshshopid As shopid, dateadd(dd,0, datediff(dd,0, poshbilldate)) As billdate,       
   -- poshcAshaccid As accountid, COnvert(numeric(18,8), Sum( fb_pd_reusedqty*fb_pd_Rate  ))  As amount,      
   -- COnvert(numeric(18,8), Sum( fb_pd_reusedqty*fb_pd_Rate ) * poshdepexrate)  As damount,      
   -- COnvert(numeric(18,8), Sum( fb_pd_reusedqty*fb_pd_Rate ) * poshexchangerate) As camount,      
   -- 1 As cAsh, 'fandb' As transtype, poshdepartmentid departmentid ,0 as PdChqCancelled  
   -- ,ISNULL(poshUserId,0) as UserID     
   -- From  losposfandbheader ph,fb_processdetail pd   Where       
   -- ph.poshshopid = pd.fb_pd_outletid And ph.poshbillid = pd.fb_pd_processid And ph.poshcancelled=0
   -- and poshBillType in ('CA','VO','VCA')        
   -- Group By poshcompanyid , poshshopid , poshbilldate ,poshbillid, poshcAshaccid ,       
   -- poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate,ISNULL(poshUserId,0)   
--RefNo-6-----------------------------------------------end-----------------------------------------------------------------  


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Do a Receipt with Ruffiya Customer and Dollar account, wrong values are displaying in report. on 29.09.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionGSTSeparately')
   DROP view dbo.vwDailySalesCollectionGSTSeparately
GO
--Last Modified on  : 12/12/02, 01/11/2004                        
--Modified by  : leo, Hariharan                           
--Comments  : v3                          
--          : Removed VwCashSalesTruncated as max tables error (256 tables) was coming                           
--          : while executing query with this view. Made vwCashSales to Refer Only Once                     
--Modified By: Benzigar S D                  
--Modified On: 23/03/2009                  
--Comments   : Added exchange rate amount in receipts               
----------------------------------------------------------------------------------------------                  
--Modified By: Regin Thangaraj        
--Modified On: 26/10/2010        
--Comments   : Corrected receipt amount calculation (RefNo-1)        
----------------------------------------------------------------------------------------------                  
--RefNo        : RefNo-2      
--Modified by  : Bijesh.B      
--Date         : 12/06/2011      
--Comments     : PD Cheque upgradation (Need to show PD Cheque amount in separate column)      
----------------------------------------------------------------------------------------------         
--RefNo        : RefNo-3      
--Modified by  : Bijesh.B      
--Date         : 31/08/2011      
--Comments     : Bugsheet (P & C/REPORTS/PandC report.xls) against ticket id CBN-603540      
--               (defect id 59) - No need to show Dummy Receipt amount with Department wise option      
----------------------------------------------------------------------------------------------        
--RefNo        : RefNo-4     
--Modified by  : AADYAKUMAR.D.V  
--Date         : 12/12/2011      
--Comments     : As per ticket NRT-913015 i am modified  
----------------------------------------------------------------------------------------------     
----------------------------------------------------------------------------------------------       
--RefNo        : Created New View 
--Created by   : Bijesh.B 
--Date         : 11/04/2012
--Ticket id    : JDJ-400367 (new report (rptdailysalescollectiondepwiseGSTSeparately) for sonee - GST separation)
--Comments     : Created new view and report (Copy of vwDailySalesCollection)
----------------------------------------------------------------------------------------------       
--RefNo        : RefNo-5     
--Modified by  : AADYAKUMAR.D.V  
--Date         : 07/05/2012
--Comments     : Added new column to synchronize with report
----------------------------------------------------------------------------------------------     
--Modified by   : Bijesh.B 
--Date          : 16/07/2012
--Ticket id     : JDJ-400367 
--Desc          : correctd values
----------------------------------------------------------------------------------------------       
--RefNo-6
--Modified by   : Bijesh.B 
--Date          : 29/07/2012
--Ticket id     : JDJ-400367 
--Desc          : Wrong figures are displaying, if Receipt is done with Rufiya customer
--                and Account is Dollar.
----------------------------------------------------------------------------------------------       

create VIEW dbo.vwDailySalesCollectionGSTSeparately AS                          
                          
select companyid,departmentid, shopid, billdate,                           
convert(numeric(18,8), sum(cashsales)) cashsales,                           
convert(numeric(18,8), sum(dcashsales)) dcashsales,                           
convert(numeric(18,8), sum(ccashsales)) ccashsales,                           
convert(numeric(18,8), sum(receipts)) receipts,                           
convert(numeric(18,8), sum(dreceipts)) dreceipts,                           
convert(numeric(18,8), sum(creceipts)) creceipts,                           
convert(numeric(18,8), sum(payments)) payments ,                          
convert(numeric(18,8), sum(dpayments)) dpayments ,                           
convert(numeric(18,8), sum(cpayments)) cpayments ,                          
convert(numeric(18,8), sum(creditsales)) creditsales,                           
convert(numeric(18,8), sum(dcreditsales)) dcreditsales,                           
convert(numeric(18,8), sum(ccreditsales)) ccreditsales,                     
convert(numeric(18,8), sum(creditcard)) as creditcard,                           
convert(numeric(18,8), sum(dcreditcard)) as dcreditcard,                           
convert(numeric(18,8), sum(ccreditcard)) as ccreditcard,                           
convert(numeric(18,8), sum(debitcard)) as debitcard,                          
convert(numeric(18,8), sum(ddebitcard)) as ddebitcard,                           
convert(numeric(18,8), sum(cdebitcard)) as cdebitcard,                          
convert(numeric(18,8), sum(localpurchase)) as localpurchase,                           
convert(numeric(18,8), sum(dlocalpurchase)) as dlocalpurchase,                          
convert(numeric(18,8), sum(clocalpurchase)) as clocalpurchase,
-- RefNo-5  
convert(numeric(18,8), sum(Exchange)) as Exchange,           
convert(numeric(18,8), sum(dExchange)) as dExchange,  
convert(numeric(18,8), sum(cExchange)) as cExchange,  
convert(numeric(18,8), sum(GoodsReturn)) as GoodsReturn,           
convert(numeric(18,8), sum(dGoodsReturn)) as dGoodsReturn,  
convert(numeric(18,8), sum(cGoodsReturn)) as cGoodsReturn 
-- RefNo-5      
--RefNo-2 start -------------------      
,convert(numeric(18,8), sum(PdChequeSales)) PdChequeSales,                                 
convert(numeric(18,8), sum(dPdChequeSales)) dPdChequeSales,                                 
convert(numeric(18,8), sum(cPdChequeSales)) cPdChequeSales      
--RefNo-2 end -------------------                             
,convert(numeric(18,8),sum(GSTAmount))GSTAmount,
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount
  
from                          
(select cs.companyid ,departmentid, shopid, billdate,                         
case when cash=1 and (am.misc='CA' or am.misc is null) then sum(Amount) else 0 end cashsales,                           
case when cash=1 and (am.misc='CA' or am.misc is null) then sum(damount) else 0 end dcashsales,                         
case when cash=1 and (am.misc='CA' or am.misc is null) then sum(camount) else 0 end  ccashsales,                        
case when cash=1 and am.misc='CC' then sum(Amount) else 0 end creditcard,                           
case when cash=1 and am.misc='CC' then sum(damount) else 0 end  dcreditcard,                         
case when cash=1 and am.misc='CC' then sum(camount) else 0 end  ccreditcard,                        
case when cash=1 and am.misc='DC' then sum(Amount) else 0 end debitcard,                           
case when cash=1 and am.misc='DC' then sum(damount) else 0 end  ddebitcard,                         
case when cash=1 and am.misc='DC' then sum(camount) else 0 end  cdebitcard,                        
0.0 as receipts, 0.0 as dreceipts, 0.0 as creceipts,                         
0.0 as payments, 0.0 as dpayments, 0.0 as cpayments,      
      
--RefNo-2 start commented below -----------------------------                            
/*      
case when cash=0 then sum(Amount) else 0 end creditsales,                           
case when cash=0 then sum(damount) else 0 end  dcreditsales,                         
case when cash=0 then sum(camount) else 0 end  ccreditsales,                        
*/      
case when cash=0 and (transtype<>'PD CHEQUE') then sum(Amount) else 0 end creditsales,                                 
case when cash=0 and (transtype<>'PD CHEQUE') then sum(damount) else 0 end  dcreditsales,                               
case when cash=0 and (transtype<>'PD CHEQUE') then sum(camount) else 0 end  ccreditsales,                              
--RefNo-2 ends ----------------------------------------------      
0.0 as localpurchase,                           
0.0 as dlocalpurchase , 0.0 as clocalpurchase                            
--RefNo-2 start ---------------------------------------------  
-- RefNo-5  
,0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn 
-- RefNo-5                            
,case when cash=0 and (transtype='PD CHEQUE') then sum(Amount) else 0 end PdChequeSales,                           
case when cash=0 and (transtype='PD CHEQUE') then sum(damount) else 0 end dPdChequeSales,                         
case when cash=0 and (transtype='PD CHEQUE') then sum(camount) else 0 end cPdChequeSales                        
--RefNo-2 ends ---------------------------------------------                            
,sum(GSTAmount)GSTAmount,sum(dGSTAmount)dGSTAmount,sum(cGSTAmount)cGSTAmount
--,case when cash=1 then sum(GSTAmount) else 0 end  GSTAmount,
--case when cash=1 then sum(dGSTAmount) else 0 end  dGSTAmount,
--case when cash=1 then sum(cGSTAmount) else 0 end  cGSTAmount

from vwCAshSalesGSTSeparately cs left outer join aaccountmaster am   on                        
cs.accountid = am.accountid and cs.companyid = am.companyid                      
group by cs.companyid ,departmentid, shopid, billdate, am.misc, cash -- cashsales                           
,transtype --RefNo2                      
          
union all                          
      
select drcompanyid, drdepartmentid, drshopid, drdate, 0.0 as cashsales, 0.0 as dcashsales,                           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,                           
0.0 as ddebitcard, 0.0 as cdebitcard,                           
convert(numeric(18,8),sum(drAmount)) receipts,                           
convert(numeric(18,8),sum(drAmount)* drdepexrate) dreceipts,                           
convert(numeric(18,8),sum(drAmount)*drexchangerate) creceipts,                           
0.0 as payments, 0.0 as dpayments,                       
0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales,                           
0.0 as ccreditsales, 0.0 as localpurchase,                   
0.0 as dlocalpurchase, 0.0 as clocalpurchase,
-- RefNo-5  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn 
-- RefNo-5                            
--RefNo-2 start -------------------      
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                                 
0.0 as cPdChequeSales      
--RefNo-2 end -------------------                                
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
from losDummyReceiptHeader rh, acustomermaster cm                         
where       
drcancelledremarks='Accounted' and  -- RefNo-3 added      
drcancelled = 0                           
and rh.drcustomerid = cm.customerid                           
and rh.drcompanyid = cm.companyid                           
group by drcompanyid, drdepartmentid, drshopid, drdate                          
,drdepexrate,drexchangerate      
union all                           
                         
--selects the receipts done in the HQ for the shop other than the shop receipts by checking the                           
--exchange nature field. iF THE exchangenature field is null then the receipt is done only in                           
--hq and if the exchangenature field is not null then the shop receipts will only taken                          
--for receipts                          
select rh.companyid, rh.departmentid, rd.shopid, rh.receiptdate, 0.0 as cashsales,                           
0.0 as dcashsales,                           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,                           
0.0 as ddebitcard, 0.0 as cdebitcard,                           
--convert(numeric(18,8),sum(rd.AmountReceived)) receipts,                           
--convert(numeric(18,8),sum(rd.AmountReceived )) dreceipts,                           
--convert(numeric(18,8),sum(rd.AmountReceived )) creceipts,   
--RefNo-4  --------------------------start--------------------------------------             
------------------ Benzigar code -------------------------------------------  
--convert(numeric(18,8),sum(rh.customeramount)) receipts,                         
--convert(numeric(18,8),sum(rh.Amount*rh.depexrate )) dreceipts,                         
--convert(numeric(18,8),sum(rh.Amount*rh.exchangerate)) creceipts,                
convert(numeric(18,8),sum(rd.amountreceived)) receipts,                           
--RefNo-6 start commented and added
	--convert(numeric(18,8),sum(rd.amountreceived)*rh.depexrate) dreceipts,                           
	--convert(numeric(18,8),sum(rd.amountreceived)*rh.exchangerate) creceipts,   
convert(numeric(18,8),sum(rd.amountreceived)*cusvenaccexrate*rh.depexrate) dreceipts,                           
convert(numeric(18,8),sum(rd.amountreceived)*cusvenaccexrate*rh.exchangerate) creceipts,   
--RefNo-6 ends
           
-------------------------------------------------------------                
--RefNo-4  ---------------------------end---------------------------------------  
-- Corrected receipt amount calculation. Old code commented above. (RefNo-1)        
--convert(numeric(18,8),sum(rd.AmountReceived)) receipts,                           
--convert(numeric(18,8),sum(rd.AmountReceived*rh.depexrate)) dreceipts,                           
--convert(numeric(18,8),sum(rd.AmountReceived*rh.exchangerate)) creceipts,         
0.0 as payments,                           
0.0 as dpayments,                           
0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales, 0.0 as ccreditsales,                           
0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase,
-- RefNo-5  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn
-- RefNo-5                               
--RefNo-2 start -------------------      
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                                 
0.0 as cPdChequeSales      
--RefNo-2 end -------------------     
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
from receiptvoucherheader rh, receiptvoucherdetails rd                           
where rh.receiptid = rd.receiptid                           
and rh.companyid = rd.companyid                          
and rh.cancelled=0                          
and ((rh.dummyreceiptid is null and rh.recshopid is null)                           
      or (rh.dummyreceiptid=0 and rh.recshopid=0))                        
group by rh.companyid,rh.departmentid, rd.shopid, rh.receiptdate                    
,depexrate,exchangerate,cusvenaccexrate                    
union all                       
-- For Populating Other Receipts                     
-- Other Receipts is done in Departments So ShopId will be 0                    
select rh.companyid, rh.departmentid, 0 shopid, rh.receiptdate, 0.0 as cashsales,                           
0.0 as dcashsales,                           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,                           
0.0 as ddebitcard, 0.0 as cdebitcard,                           
convert(numeric(18,8),sum(Amount)) receipts,                           
convert(numeric(18,8),sum(Amount) * depexrate) dreceipts,                           
convert(numeric(18,8),sum(Amount)* exchangerate) creceipts, 0.0 as payments,                           
0.0 as dpayments,                           
0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales, 0.0 as ccreditsales,                           
0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase,
-- RefNo-5  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn
-- RefNo-5                               
--RefNo-2 start -------------------      
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                                 
0.0 as cPdChequeSales     
--RefNo-2 end -------------------                                
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount   
from receiptvoucherheader rh                          
where  rh.cancelled=0                     
and rh.ReceiptID not in (select ReceiptID from ReceiptVoucherDetails)                  
and ((rh.dummyreceiptid is null and rh.recshopid is null)                           
      or (rh.dummyreceiptid=0 and rh.recshopid=0))                
group by rh.companyid,rh.departmentid, rh.receiptdate                    
,depexrate, exchangerate                    
union all                          
                          
select phcompanyid,phdepartmentid, phshopid, phPaymentDate, 0.0 as cashsales, 0.0 as dcashsales,                           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,                           
0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts, 0.0 as creceipts,                      
convert(numeric(18,8),sum(phAmount)) as payments,                           
convert(numeric(18,8),sum(phAmount)* phdepexrate) as dpayments,                           
convert(numeric(18,8),sum(phAmount)* phexchangerate) as cpayments,                           
0.0 as creditsales , 0.0 as dcreditsales, 0.0 as ccreditsales, 0.0 as localpurchase,                           
0.0 as dlocalpurchase, 0.0 as clocalpurchase,
-- RefNo-5  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                             
-- RefNo-5  
--RefNo-2 start -------------------      
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                                 
0.0 as cPdChequeSales      
--RefNo-2 end -------------------      
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
from LOsPaymentVoucherHeader ph                           
where phcancelled = 0                      
group by phcompanyid, phdepartmentid, phshopid, phPaymentDate                          
,phdepexrate,phexchangerate                          
union all                          
--local purchase - madhu 23/08/01                          
--select lh.lphcompanyid,lh.lphdepartmentid,lh.lphshopid,lh.lphbilldate, 0.0 cashsales,                           
--0.0 dcashsales, 0.0 ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard,                          
--0.0 as debitcard, 0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts,                          
--0.0 as creceipts, 0.0 as payments, 0.0 as dpayments, 0.0 as cpayments, 0.0 as creditsales,                           
--0.0 as dcreditsales, 0.0 as ccreditsales, convert(numeric(18,8),sum(lphbillamount)) as localpurchase,                          
--convert(numeric(18,8),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,                           
--convert(numeric(18,8),sum(lphbillamount*lphexchangerate)) as clocalpurchase                          
----RefNo-2 start -------------------      
--,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                                 
--0.0 as cPdChequeSales      
----RefNo-2 end -------------------                                
--,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
--from loslocalpurchaseheader lh,adepartmentmaster d where                          
--lh.lphDepartmentID=d.departmentid  and lh.lphcashpurchase=1  and lphcancelled=0                          
--group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate) summary                           
--group by companyid ,departmentid, shopid, billdate

select lh.lphcompanyid,lh.lphdepartmentid,lh.lphshopid,lh.lphbilldate, 0.0 cashsales,                           
0.0 dcashsales, 0.0 ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard,                          
0.0 as debitcard, 0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts,              
0.0 as creceipts, 0.0 as payments, 0.0 as dpayments, 0.0 as cpayments, 0.0 as creditsales,                           
0.0 as dcreditsales, 0.0 as ccreditsales,
--convert(numeric(18,8),sum(lphbillamount)) as localpurchase1,                          
--convert(numeric(18,8),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,                           
--convert(numeric(18,8),sum(lphbillamount*lphexchangerate)) as clocalpurchase                          
convert(numeric(18,8),sum(lphbillamount-isnull(ld.lpdItemTaxAmount,0))) as localpurchase,   
convert(numeric(18,8),sum(lphbillamount-isnull(ld.lpdItemTaxAmount,0))* lphdepexrate) as dlocalpurchase,                           
convert(numeric(18,8),sum(lphbillamount-isnull(ld.lpdItemTaxAmount,0))*lphexchangerate) as clocalpurchase,
-- RefNo-5  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                            
-- RefNo-5  
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
--RefNo-2 ends -------------------
,convert(numeric(18,8),sum(isnull(ld.lpdItemTaxAmount,0))) as GSTAmount,
convert(numeric(18,8),sum(isnull(ld.lpdItemTaxAmount,0))*lphdepexrate) as dGSTAmount,
convert(numeric(18,8),sum(isnull(ld.lpdItemTaxAmount,0))*lphexchangerate) as cGSTAmount
from loslocalpurchaseheader lh,adepartmentmaster d,
(select lpdShopID,lpdBillID , SUM(isnull(lpdItemTaxAmount,0))lpdItemTaxAmount 
 from loslocalpurchaseDetail group by lpdShopID,lpdBillID)ld
where                          
lh.lphDepartmentID=d.departmentid and lh.lphcashpurchase=1  and lphcancelled=0 
and lh.lphBillID = ld.lpdBillID and lh.lphShopID = ld.lpdShopID                            
group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate
,lphdepexrate,lphexchangerate
) summary                           
group by companyid ,departmentid, shopid, billdate



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

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwShopItemSalesGstSeparately')
   DROP view dbo.vwShopItemSalesGstSeparately
GO
  
--Modified on  : 20/12/02                                
--Modified by   : Hariharan R                                
--Comments  : v3                                
--Added reexporting transaction                                
--------------------------------------------------------------------------                                
-- Modified by     : Kishore                                
-- Modified on  : 12/06/2003                                
-- Comments  : Added the aMount, cAmount and dAmount columns                                
--                        (On comparison with v2)                                
--------------------------------------------------------------------------                                
                                
 --------------------------------------------------------------------                                
--Modified on                  : 27/08/2003                                
--Modified by                  : Reji Abraham                                
--Comments                     : Replaced table losserviceheader by losserviceinvheader                                    
--          : and modified fields, previous fields are alias names                                
--          :given ihTransFinised = 1 condition check to pick the confirmed                                
--          :Transactions Only.                                
                                
-------------------------------------------------------------------------------------                                
--Modified on                  : 15/04/04                                
--Modified by                  : venkitesh                                
--Comments                     : Replaced - symbol for goods return case and Given convert for getting accurated figure                              
-------------------------------------------------------------------------------------                                
--Modified on                  : 26/08/08                                
--Modified by                  : Benzigar                                
--Comments                     : Added condition ihNoofOCDetails=0 in specialinvoice to avoid return before despatch items from daily sales                             
--                             : Added case for Direct invoice - return before despatch                            
---------------------------------------------------------------------------------------                        
--Modified on                  : 05/08/09                                
--Modified by                  : Nidheesh                                 
--Comments                     : taken the reqqty as negative in the case of RBD of (4  Direct invoice - return before despatch )                             
-- : removed the minus sign of unitprice,margin                 
---------------------------------------------------------------------------------------              
--Modified on                  : 23/10/09                    
--Modified by                  : Nidheesh                    
--Comments                     : Included the requiremnet of adding custom price to cost price for shop credit invoice.(case-2)                  
--                             : checked whether the shop is BondedWareHouse or not and  'AddCustomDutyToCostPrice'.               
---------------------------------------------------------------------------------------                        
--Modified on                  : 10/11/09                                
--Modified by                  : Regin                
--Comments                     : To get the margin of sale correctly modified the margin portion                 
---------------------------------------------------------------------------------------                        
--Modified on                  : 10/11/09      
--Modified by                  : Regin                
--Comments : In Goods Exchange part, sedquantity was replaced by sedExchangeQty since sedExchangeQty is the returned qty                
---------------------------------------------------------------------------------------                        
--Modified on                  : 05/12/2009              
--Modified by                  : Benzigar                
--Comments                     : In invoice part added case condition to handle divided by 0 problem               
---------------------------------------------------------------------------------------                        
--Modified on                  : 07/08/2010                
--Modified by                  : Sreejith G A                
--Comments                     : Added an additional field Actual Price of the item from Transaction table           
---------------------------------------------------------------------------------------                        
--Modified on                  : 17/11/2010                
--Modified by                  : Abhishek CS               
--Comments                     : customerid added for koddoo salesanalysisbyitem(actual)report need to filter by customer        
---------------------------------------------------------------------------------------                        
--Modified on                  : 19/05/2011                
--Modified by                  : Aadyakumar.D.V               
--Comments                     : FRS-409830,divide by zero errror       
---------------------------------------------------------------------------------------                        
--Modified on                  : 18/06/2011                
--Modified by                  : Nidheesh P V             
--Comments                     : Added ELSE part in the checking of wheather quantity is zero or not.    
--Modified Area       : All reports which are showing sales of items.    
--Reference        : RefNo:1    
---------------------------------------------------------------------------------------           
  
--------------------------------------------------------------------------     
--Created on                   : 20/04/2012            
--Comments                     : New view created for sonee (copy of spSalesAnalysisByItem)  
--                               for new report rptSalesByItemShopwiseGSTSeparately.rpt  
-- Tikect id                   : JDJ-400367 (Sonee)  
---------------------------------------------------------------------------------------------     
--Modified by   : Bijesh.B 
--Date          : 16/07/2012
--Ticket id     : JDJ-400367 
--Desc          : correctd values
----------------------------------------------------------------------------------------------       
--Modified by   : Bijesh.B 
--Date          : 01/10/2012
--Ticket id     : JDJ-400367 
--Desc          : correctd Gst Amount in case of goods exchange
----------------------------------------------------------------------------------------------       

CREATE VIEW [dbo].[vwShopItemSalesGstSeparately] AS                                
-- 1                                
select                       
 posditemid,          
 convert(numeric(18,8), posdActualUnitPrice *  poshExchangeRate) cActualUnitPrice,  --sree                     
 convert(numeric(18,8), posdActualUnitPrice *  poshDepExRate) dActualUnitPrice,   --sree              
 convert(numeric(18,8), posdActualUnitPrice) ActualUnitPrice,  --sree              
 --convert(numeric(18,8), (posdUnitPrice /CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END) *  poshExchangeRate) cUnitPrice,   --RefNo:1                    
 --convert(numeric(18,8), (posdUnitPrice / CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END) *  poshDepExRate) dUnitPrice,     --RefNo:1                   
 --convert(numeric(18,8), (posdUnitPrice / CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END)) posdUnitPrice,                   --RefNo:1     
 convert(numeric(18,8), (posdUnitPrice/CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END)-(isnull(posdItemTaxAmount,0)/CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END)  *  poshExchangeRate) cUnitPrice,   --RefNo:1                   
 convert(numeric(18,8), (posdUnitPrice/CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END)-(isnull(posdItemTaxAmount,0)/CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END) *  poshDepExRate) dUnitPrice,     --RefNo:1                   
 convert(numeric(18,8), (posdUnitPrice/CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END)-(isnull(posdItemTaxAmount,0)/CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END)) posdUnitPrice,                   --RefNo:1     
 posdquantity,posdRateType, poshBilldate,poshbillID,                      
 poshBillNo,poshShopID, posdcostprice costprice, posdcostprice * poshDepExRate dcostprice,                       
 posdcostprice * poshExchangeRate ccostprice, 'S' as type,                       
-- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                
-- ((posdUnitPrice / posdquantity) - posdcostprice) margin,                    
-- ((posdUnitPrice / posdquantity) - posdcostprice) * poshDepExRate  dmargin,                       
-- ((posdUnitPrice / posdquantity) - posdcostprice) * poshExchangeRate  cmargin,                       
  
 -- posdUnitPrice-posdcostprice*posdquantity margin,                       
 --(posdUnitPrice-posdcostprice*posdquantity)* poshDepExRate dmargin,                       
 --(posdUnitPrice-posdcostprice*posdquantity)* poshExchangeRate cmargin,                       
  (posdUnitPrice-isnull(posdItemTaxAmount,0))-posdcostprice*posdquantity margin,                       
 ((posdUnitPrice-isnull(posdItemTaxAmount,0))-posdcostprice*posdquantity)* poshDepExRate dmargin,                       
 ((posdUnitPrice-isnull(posdItemTaxAmount,0))-posdcostprice*posdquantity)* poshExchangeRate cmargin,                       
   
 --convert(numeric(18,8),posdUnitPrice) Amount,  
 --convert(numeric(18,8),posdUnitPrice * poshExchangeRate) cAmount,                      
 --convert(numeric(18,8),posdUnitPrice * poshDepExRate) dAmount ,          
 convert(numeric(18,8),(posdUnitPrice-isnull(posdItemTaxAmount,0))) Amount,  
 convert(numeric(18,8),(posdUnitPrice-isnull(posdItemTaxAmount,0)) * poshExchangeRate) cAmount,                      
 convert(numeric(18,8),(posdUnitPrice-isnull(posdItemTaxAmount,0)) * poshDepExRate) dAmount ,          
  
 convert(numeric(18,8),posdActualUnitPrice * posdquantity) ActualAmount,--sree          
 convert(numeric(18,8),posdActualUnitPrice * poshExchangeRate *posdquantity) cActualAmount,  --sree                    
 convert(numeric(18,8),posdActualUnitPrice * poshDepExRate *posdquantity) dActualAmount,     --sree                 
 poshcustomerid,  
 convert(numeric(18,8),(isnull(posdItemTaxAmount,0)))GSTAmount,  
 convert(numeric(18,8),(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,  
 convert(numeric(18,8),(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount  
from                       
 losposdetail, losposheader                       
where                       
 poshBillid = posdBillid and poshShopid = posdshopid AND POSHCANCELLED = 0                
                                 
union all                                
---- 2                                 
--select                                 
-- iditemid, convert(numeric(18,8),                                 
-- (idUnitPrice / idquantity)  *  ihExchangeRate) cUnitPrice,                                 
-- convert(numeric(18,8), (idUnitPrice / idquantity)  *  ihDepExRate) dUnitPrice,                                 
-- convert(numeric(18,8), (idUnitPrice / idquantity))  posdUnitPrice,                                 
-- idquantity, idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid,idcostprice,                                 
-- idcostprice * ihDepExRate,idcostprice * ihExchangeRate, 'S',                                
-- -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009              
-- -- ((idUnitPrice / idquantity) * ihExchangeRate - idcostprice) margin,                                 
-- -- ((idUnitPrice / idquantity) - idcostprice) * ihDepExRate  dmargin,                                
-- -- ((idUnitPrice / idquantity) - idcostprice) * ihExchangeRate cmargin,                                   
-- idUnitPrice-idcostprice*idquantity margin,                                 
-- (idUnitPrice-idcostprice*idquantity) * ihDepExRate  dmargin,                                
-- (idUnitPrice-idcostprice*idquantity) * ihExchangeRate cmargin,                                   
-- convert(numeric(18,8),idUnitPrice) Amount,convert(numeric(18,8),idUnitPrice * ihExchangeRate) cAmount,                        
-- convert(numeric(18,8),idUnitPrice * ihDepExRate) dAmount                                
--from                                 
-- losinvoiceheader ih, losinvoicedetail invd                                 
--                                
--where                                 
-- ih.ihInvoiceid = invd.idInvoiceid  and ih.ihshopid = invd.idshopid AND                                
-- IHCANCELLED = 0 and ihproforma = 0 and ihtype = 'i'                                
          
-- 2  shop credit invoice                             
select                     
 iditemid,          
 convert(numeric(18,8), idActualUnitPrice *  ihexchangerate) cActualUnitPrice,  --sree                     
 convert(numeric(18,8), idActualUnitPrice *  ihDepExRate) dActualUnitPrice,   --sree              
 convert(numeric(18,8), idActualUnitPrice) ActualUnitPrice,  --sree           
 --case when (idquantity<>0) then  convert(numeric(18,8),(idUnitPrice / CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)  *  ihExchangeRate) else 0 end  cUnitPrice,   --RefNo:1                         
 --case when (idquantity<>0) then convert(numeric(18,8),(idUnitPrice / CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)  *  ihDepExRate) else 0 end dUnitPrice,       --RefNo:1           
 --case when (idquantity<>0) then (idUnitPrice / CASE WHEN idquantity=0 THEN 1 ELSE idquantity END) else 0 end posdUnitPrice,                                           --RefNo:1     
  
 case when (idquantity<>0) then convert(numeric(18,8),(idUnitPrice / CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)-(isnull(idItemTaxAmount,0)/CASE WHEN idquantity=0 THEN 1 ELSE idquantity END) *  ihExchangeRate) else 0 end  cUnitPrice,   --RefNo:1  
 case when (idquantity<>0) then convert(numeric(18,8),(idUnitPrice / CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)-(isnull(idItemTaxAmount,0)/CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)  *  ihDepExRate) else 0 end dUnitPrice,       --RefNo:1  
 case when (idquantity<>0) then convert(numeric(18,8),(idUnitPrice / CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)-(isnull(idItemTaxAmount,0)/CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)) else 0 end posdUnitPrice,                               
--RefNo:1     
 idquantity, idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid,              
 case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then idcostprice+(idcostprice*m.CustomCategoryPercent/100) else idcostprice end  idcostprice,                     
 case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then (idcostprice * ihDepExRate)+((idcostprice * ihDepExRate)*m.CustomCategoryPercent/100) else idcostprice * ihDepExRate end ,              
 case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then (idcostprice * ihExchangeRate)+((idcostprice * ihExchangeRate)*m.CustomCategoryPercent/100) else idcostprice * ihExchangeRate end ,'S',                    
              
-- case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then ((idUnitPrice / idquantity) * ihExchangeRate - (idcostprice+(idcostprice*m.CustomCategoryPercent/100))) else((idUnitPrice / idquantity) * ihExchangeRate - idcostprice)end margin,          
-- case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then ((idUnitPrice / idquantity) - (idcostprice+(idcostprice*m.CustomCategoryPercent/100))) * ihDepExRate else((idUnitPrice / idquantity) - idcostprice) * ihDepExRate end dmargin,              
-- case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then ((idUnitPrice / idquantity) - (idcostprice+(idcostprice*m.CustomCategoryPercent/100))) * ihExchangeRate else((idUnitPrice / idquantity) - idcostprice) * ihExchangeRate end cmargin,        
      
 --case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then idUnitPrice-(idcostprice+(idcostprice*m.CustomCategoryPercent/100))*idquantity else(idUnitPrice-idcostprice*idquantity)end margin,                     
 --case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then (idUnitPrice-(idcostprice+(idcostprice*m.CustomCategoryPercent/100))*idquantity) * ihDepExRate else(idUnitPrice-idcostprice*idquantity) * ihDepExRate end dmargin,                    
 --case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then (idUnitPrice-(idcostprice+(idcostprice*m.CustomCategoryPercent/100))*idquantity) * ihExchangeRate else(idUnitPrice-idcostprice*idquantity) * ihExchangeRate end cmargin,                    

 case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then (idUnitPrice- isnull(idItemTaxAmount,0))-(idcostprice+(idcostprice*m.CustomCategoryPercent/100))*idquantity                    
   else((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*idquantity)end margin,                     
 case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then ((idUnitPrice-isnull(idItemTaxAmount,0))-(idcostprice+(idcostprice*m.CustomCategoryPercent/100))*idquantity) * ihDepExRate    
  else((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*idquantity) * ihDepExRate end dmargin,                    
 case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then ((idUnitPrice-isnull(idItemTaxAmount,0)) -(idcostprice+(idcostprice*m.CustomCategoryPercent/100))*idquantity) * ihExchangeRate 
 else((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*idquantity) * ihExchangeRate end cmargin,                      --convert(numeric(18,8),idUnitPrice) Amount,  
 --convert(numeric(18,8),idUnitPrice * ihExchangeRate) cAmount,                    
 --convert(numeric(18,8),idUnitPrice * ihDepExRate) dAmount,         
 convert(numeric(18,8),idUnitPrice-isnull(idItemTaxAmount,0))Amount,  
 convert(numeric(18,8),(idUnitPrice-isnull(idItemTaxAmount,0))* ihExchangeRate) cAmount,                    
 convert(numeric(18,8),(idUnitPrice-isnull(idItemTaxAmount,0))* ihDepExRate) dAmount,           
   
 convert(numeric(18,8),idActualUnitPrice * idquantity) ActualAmount,--sree          
 convert(numeric(18,8),idActualUnitPrice * ihexchangerate *idquantity) cActualAmount,  --sree                    
 convert(numeric(18,8),idActualUnitPrice * ihDepExRate *idquantity) dActualAmount,     --sree                    
 ih.ihCustomerID,  
   
 convert(numeric(18,8),(isnull(idItemTaxAmount,0)))GSTAmount,  
 convert(numeric(18,8),(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount  
from                     
 losinvoiceheader ih, losinvoicedetail invd               
 LEFT OUTER JOIN aItem a ON  a.ItemID=iditemid              
 LEFT OUTER JOIN acustomsmaster m ON  m.CustomID=a.CustomID              
 ,ashops                 
where                     
 ih.ihInvoiceid = invd.idInvoiceid  and ih.ihshopid = invd.idshopid AND                    
 IHCANCELLED = 0 and ihproforma = 0 and ihtype = 'i' and ihcashinvoice=0               
  and ih.ihShopID=shopid                 
                                
union all                                
--3                                
select                                 
 seditemid,              
 convert(numeric(18,8), sedActualUnitPrice *  sehExchangeRate) cActualUnitPrice,  --sree                     
 convert(numeric(18,8), sedActualUnitPrice *  sehDepExRate) dActualUnitPrice,   --sree              
 convert(numeric(18,8), sedActualUnitPrice) ActualUnitPrice,  --sree                              
 --convert(numeric(18,8),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehExchangeRate) cUnitPrice,   --RefNo:1                               
 --convert(numeric(18,8),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehDepExRate) dUnitPrice,      --RefNo:1                           
 --convert(numeric(18,8),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) ) UnitPrice,                     --RefNo:1             
convert(numeric(18,8),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END)-(isnull(sedItemTaxAmount,0)/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehExchangeRate) cUnitPrice,   --RefNo:1                               
convert(numeric(18,8),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END)-(isnull(sedItemTaxAmount,0)/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehDepExRate) dUnitPrice,      --RefNo:1                           
convert(numeric(18,8),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END)-(isnull(sedItemTaxAmount,0)/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END)) UnitPrice,                     --RefNo:1             
  
/*  
 convert(numeric(18,8),((sedUnitPrice-(isnull(sedItemTaxAmount,0)/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END))/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehExchangeRate) cUnitPrice,   --RefNo:1                               
 convert(numeric(18,8),((sedUnitPrice-(isnull(sedItemTaxAmount,0)/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END))/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehDepExRate) dUnitPrice,      --RefNo:1                           
 convert(numeric(18,8),((sedUnitPrice-(isnull(sedItemTaxAmount,0)/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END)) /CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) ) UnitPrice,                     --RefNo:1             
*/  
  
 sedquantity, sedRateType,sehExchangeDate,sehExchangeID,sehExchangeNo,sehShopID,       
 sedcostprice, sedcostprice *  sehDepExRate, sedcostprice * sehExchangeRate, 'S',                                
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                
 -- ((sedUnitPrice / sedquantity)  - sedcostprice) margin,                                
 -- ((sedUnitPrice / sedquantity) - sedcostprice) *  sehDepExRate  dmargin,                                
 -- ((sedUnitPrice / sedquantity) - sedcostprice) *  sehExchangeRate  cmargin,                                
 -- sedUnitPrice-sedcostprice*sedquantity margin,                                
 --(sedUnitPrice-sedcostprice*sedquantity) *  sehDepExRate  dmargin,                                
 --(sedUnitPrice-sedcostprice*sedquantity) *  sehExchangeRate  cmargin,                                
  (sedUnitPrice-isnull(sedItemTaxAmount,0))-sedcostprice*sedquantity margin,                                
 ((sedUnitPrice-isnull(sedItemTaxAmount,0))-sedcostprice*sedquantity) *  sehDepExRate  dmargin,                                
 ((sedUnitPrice-isnull(sedItemTaxAmount,0))-sedcostprice*sedquantity) *  sehExchangeRate  cmargin,                                
   
 --convert(numeric(18,8),sedUnitPrice)  Amount,  
 --convert(numeric(18,8),sedUnitPrice * sehExchangeRate) cAmount,                                
 --convert(numeric(18,8),sedUnitPrice * sehDepExRate) dAmount,          
 convert(numeric(18,8),sedUnitPrice-isnull(sedItemTaxAmount,0))  Amount,  
 convert(numeric(18,8),(sedUnitPrice-isnull(sedItemTaxAmount,0)) * sehExchangeRate) cAmount,                                
 convert(numeric(18,8),(sedUnitPrice-isnull(sedItemTaxAmount,0)) * sehDepExRate) dAmount,          
    
 convert(numeric(18,8),sedActualUnitPrice * sedquantity) ActualAmount,--sree          
 convert(numeric(18,8),sedActualUnitPrice * sehExchangeRate *sedquantity) cActualAmount,  --sree                    
 convert(numeric(18,8),sedActualUnitPrice * sehDepExRate *sedquantity) dActualAmount,     --sree                                
 0,  
convert(numeric(18,8),(isnull(sedItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
convert(numeric(18,8),(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount        
from               
 losposexchangeheader,losposexchangedetail                                 
where                                 
 sedExchangeid = sehExchangeID and sedShopID = sehShopid and                                 
 SEHCANCELLED = 0 and sedbillorexchange  = 'E'                                
                                 
union all                                
-- 4                                 
select                                 
 iditemid,           
 convert(numeric(18,8), idActualUnitPrice *  ihExchangeRate) cActualUnitPrice,  --sree                     
 convert(numeric(18,8), idActualUnitPrice *  ihDepExRate) dActualUnitPrice,   --sree              
 convert(numeric(18,8), idActualUnitPrice) ActualUnitPrice,  --sree           
 --convert(numeric(18,8),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,   --RefNo:1                                
 --convert(numeric(18,8),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,      --RefNo:1                  
 --convert(numeric(18,8),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)) UnitPrice ,reqqty,               --RefNo:1                   
 convert(numeric(18,8),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,   --RefNo:1                                
 convert(numeric(18,8),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,      --RefNo:1                  
 convert(numeric(18,8),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)) UnitPrice ,reqqty,               --RefNo:1                   
 idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,                                 
 idcostprice * ihDepExRate, idcostprice * ihExchangeRate, 'S',                                 
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                
 -- ((idUnitPrice / reqqty) -idcostprice) margin,                                 
 -- ((idUnitPrice / reqqty)  -idcostprice) *  ihDepExRate dmargin ,                                
 -- ((idUnitPrice / reqqty)  -idcostprice) *  ihExchangeRate cmargin,                                 
   
 -- idUnitPrice- idcostprice*reqqty margin,                                 
 --(idUnitPrice- idcostprice*reqqty) *  ihDepExRate dmargin ,                                
 --(idUnitPrice- idcostprice*reqqty) *  ihExchangeRate cmargin,                                 
 (idUnitPrice-isnull(idItemTaxAmount,0))- idcostprice*reqqty margin,                                 
 ((idUnitPrice-isnull(idItemTaxAmount,0))- idcostprice*reqqty) *  ihDepExRate dmargin ,                                
 ((idUnitPrice-isnull(idItemTaxAmount,0))- idcostprice*reqqty) *  ihExchangeRate cmargin,                                 
   
 --convert(numeric(18,8),idUnitPrice) Amount,  
 --convert(numeric(18,8),idUnitPrice * ihExchangeRate)  cAmount,                                 
 --convert(numeric(18,8),idUnitPrice * ihDepExRate)  Amount,          
 convert(numeric(18,8),idUnitPrice-isnull(idItemTaxAmount,0)) Amount,  
 convert(numeric(18,8),(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate)  cAmount,                                 
 convert(numeric(18,8),(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate)  Amount,          
   
 convert(numeric(18,8),idActualUnitPrice * reqqty) ActualAmount,--sree          
 convert(numeric(18,8),idActualUnitPrice * ihExchangeRate *reqqty) cActualAmount,  --sree                    
 convert(numeric(18,8),idActualUnitPrice * ihDepExRate *reqqty) dActualAmount,     --sree          
 IhCustomerID,  
 convert(numeric(18,8),(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount                           
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader                                 
where                                 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                              
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                
 and IhTransFinished = 1 and ihNoofOCDetails=0                            
                             
union all                                
-- 4  Direct invoice - return before despatch                    
select                                 
 iditemid,           
 convert(numeric(18,8), idActualUnitPrice *  ihExchangeRate) cActualUnitPrice,  --sree                     
 convert(numeric(18,8), idActualUnitPrice *  ihDepExRate) dActualUnitPrice,   --sree              
 convert(numeric(18,8), idActualUnitPrice) ActualUnitPrice,  --sree           
 --convert(numeric(18,8), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,            --RefNo:1                      
 --convert(numeric(18,8), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,               --RefNo:1                   
 --convert(numeric(18,8), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) UnitPrice,-reqqty,     --RefNo:1                             
 convert(numeric(18,8), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,            --RefNo:1                      
 convert(numeric(18,8), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,               --RefNo:1                   
 convert(numeric(18,8), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) UnitPrice,-reqqty,     --RefNo:1                             
   
 idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,                                 
 idcostprice * ihDepExRate, idcostprice * ihExchangeRate, 'R',                                
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                
 -- ((idUnitPrice / reqqty) - idcostprice) margin,                                 
 -- ((idUnitPrice / reqqty) - idcostprice) *  ihDepExRate  dmargin ,                                 
 -- ((idUnitPrice / reqqty)  - idcostprice) *  ihExchangeRate cmargin,                                 
   
 -- idUnitPrice-idcostprice*reqqty margin,                                 
 --(idUnitPrice-idcostprice*reqqty) *  ihDepExRate  dmargin ,                                 
 --(idUnitPrice-idcostprice*reqqty) *  ihExchangeRate cmargin,                                 
 (idUnitPrice-isnull(idItemTaxAmount,0)) -idcostprice*reqqty margin,                                 
 ((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*reqqty) *  ihDepExRate  dmargin ,         
 ((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*reqqty) *  ihExchangeRate cmargin,    
   
 --convert(numeric(18,8),-idUnitPrice) Amount,  
 --convert(numeric(18,8),-idUnitPrice * ihExchangeRate) cAmount,                                 
 --convert(numeric(18,8),-idUnitPrice * ihDepExRate) dAmount,          
 convert(numeric(18,8),-(idUnitPrice-isnull(idItemTaxAmount,0))) Amount,  
 convert(numeric(18,8),-(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) cAmount,                                 
 convert(numeric(18,8),-(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dAmount,   
  
 convert(numeric(18,8),-idActualUnitPrice * reqqty) ActualAmount,--sree          
 convert(numeric(18,8),-idActualUnitPrice * ihExchangeRate *reqqty) cActualAmount,  --sree                    
 convert(numeric(18,8),-idActualUnitPrice * ihDepExRate *reqqty) dActualAmount,     --sree          
 IhCustomerID,  
 convert(numeric(18,8),-(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),-(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),-(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount                           
from                                 
 losspecialinvoicedetail,losspecialinvoiceheader                                
where                                 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 0 and ihproforma = 0 and ihTransFinished = 1 and ihNoofOCDetails<>0                            
               
union all                                
-- 5                    
-- sedquantity was replaced by sedExchangeQty since sedExchangeQty is the returned qty                 
-- by Regin on 10-11-2009                             
/*                
select                                 
 seditemid, convert(numeric(18,8), -(sedUnitPrice / sedquantity)  *  sehExchangeRate) cUnitPrice ,                                
 convert(numeric(18,8), -(sedUnitPrice / sedquantity)  *  sehDepExRate) dUnitPrice,                                 
 convert(numeric(18,8), -(sedUnitPrice / sedquantity)) UnitPrice,                                 
 -sedExchangeQty, sedRateType,sehExchangeDate,sehExchangeID,sehExchangeNo,                                 
 sehShopID, sedcostprice, sedcostprice * sehDepExRate, sedcostprice * sehExchangeRate, 'R' ,                                 
  -(sedUnitPrice-sedcostprice*sedquantity) margin,                                 
  -(sedUnitPrice-sedcostprice*sedquantity) *  sehDepExRate  dmargin,                                
  -(sedUnitPrice-sedcostprice*sedquantity) *  sehExchangeRate cmargin,                     convert(numeric(18,8),- sedUnitPrice) Amount,                                
 convert(numeric(18,8),- sedUnitPrice * sehexchangerate)  cAmount,                                
 convert(numeric(18,8),- sedUnitPrice * sehDepExRate)  dAmount                                
from                                 
 losposexchangeheader, losposexchangedetail                                 
where                                 
 sedExchangeid = sehExchangeID and sedShopID = sehShopid and                                 
 SEHCANCELLED = 0 and sedbillorexchange  =  'B' and sedexchangeqty>0                                
*/          
  
select                                 
 seditemid,           
 convert(numeric(18,8), sedActualUnitPrice *  sehExchangeRate) cActualUnitPrice,  --sree                     
 convert(numeric(18,8), sedActualUnitPrice *  sehDepExRate) dActualUnitPrice,   --sree              
 convert(numeric(18,8), sedActualUnitPrice) ActualUnitPrice,  --sree           
 --convert(numeric(18,8), -(sedUnitPrice / CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)  *  sehExchangeRate) cUnitPrice ,   --RefNo:1                    
 --convert(numeric(18,8), -(sedUnitPrice / CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)  *  sehDepExRate) dUnitPrice,       --RefNo:1                           
 --convert(numeric(18,8), -(sedUnitPrice / CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)) UnitPrice,                         --RefNo:1         
 convert(numeric(18,8), -((sedUnitPrice/CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END) -(isnull(sedItemTaxAmount,0))/CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)  *  sehExchangeRate) cUnitPrice ,   --RefNo:1                     
 convert(numeric(18,8), -((sedUnitPrice/CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END) -(isnull(sedItemTaxAmount,0))/CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)  *  sehDepExRate) dUnitPrice,       --RefNo:1                      
 convert(numeric(18,8), -((sedUnitPrice/CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END) -(isnull(sedItemTaxAmount,0))/CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)) UnitPrice,                         --RefNo:1         
 -sedExchangeQty sedExchangeQty, sedRateType,sehExchangeDate poshbilldate,sehExchangeID,sehExchangeNo,                                 
 sehShopID poshShopID, sedcostprice, sedcostprice * sehDepExRate dcostprice, sedcostprice * sehExchangeRate ccostprice, 'R' typ ,                                 
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                
 -- -((sedUnitPrice / sedquantity) - sedcostprice) margin,                                 
 -- -((sedUnitPrice / sedquantity) - sedcostprice) *  sehDepExRate  dmargin,                                
 -- -((sedUnitPrice / sedquantity)  - sedcostprice) *  sehExchangeRate cmargin,                                
 - --(sedUnitPrice-sedcostprice*sedExchangeQty) margin,                                 
 - --(sedUnitPrice-sedcostprice*sedExchangeQty) *  sehDepExRate  dmargin,                                
 - --(sedUnitPrice-sedcostprice*sedExchangeQty) *  sehExchangeRate cmargin,                                
 -((sedUnitPrice-isnull(sedItemTaxAmount,0))-sedcostprice*sedExchangeQty) margin,                                 
 -((sedUnitPrice-isnull(sedItemTaxAmount,0))-sedcostprice*sedExchangeQty) *  sehDepExRate  dmargin,                                
 -((sedUnitPrice-isnull(sedItemTaxAmount,0))-sedcostprice*sedExchangeQty) *  sehExchangeRate cmargin,                                
 --convert(numeric(18,8),- sedUnitPrice) Amount,                                
 --convert(numeric(18,8),- sedUnitPrice * sehexchangerate)  cAmount,                                
 --convert(numeric(18,8),- sedUnitPrice * sehDepExRate)  dAmount ,          
 convert(numeric(18,8),- (sedUnitPrice-isnull(sedItemTaxAmount,0))) Amount,                                
 convert(numeric(18,8),- (sedUnitPrice-isnull(sedItemTaxAmount,0)) * sehexchangerate)  cAmount,                                
 convert(numeric(18,8),- (sedUnitPrice-isnull(sedItemTaxAmount,0)) * sehDepExRate)  dAmount ,          
   
 convert(numeric(18,8),-sedActualUnitPrice * sedExchangeQty) ActualAmount,--sree          
 convert(numeric(18,8),-sedActualUnitPrice * sehExchangeRate *sedExchangeQty) cActualAmount,  --sree                    
 convert(numeric(18,8),-sedActualUnitPrice * sehDepExRate *sedExchangeQty) dActualAmount ,    --sree            
 0,      
convert(numeric(18,8),-(isnull(sedItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),-(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,  
convert(numeric(18,8),-(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount        
from                                 
 losposexchangeheader, losposexchangedetail                                 
where                                 
 sedExchangeid = sehExchangeID and sedShopID = sehShopid and                                 
 SEHCANCELLED = 0 and sedbillorexchange  =  'B' and sedexchangeqty>0                 
               
union all                                
-- 6                                
-- Special invoice return                                
select                                 
 iditemid,           
 convert(numeric(18,8), idActualUnitPrice *  ihExchangeRate) cActualUnitPrice,  --sree                     
 convert(numeric(18,8), idActualUnitPrice *  ihDepExRate) dActualUnitPrice,   --sree              
 convert(numeric(18,8), idActualUnitPrice) ActualUnitPrice,  --sree          
 --convert(numeric(18,8), -(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,     --RefNo:1                             
 --convert(numeric(18,8), -(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,      --RefNo:1                         
 --convert(numeric(18,8), -(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) UnitPrice, reqqty,  --RefNo:1                                
 convert(numeric(18,8), -((idUnitPrice/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)) / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,     --RefNo:1                             
 convert(numeric(18,8), -((idUnitPrice/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)) / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,         --RefNo:1                         
 convert(numeric(18,8), -((idUnitPrice/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)) / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) UnitPrice, reqqty,  --RefNo:1                                
   
 idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,                                 
 idcostprice * ihDepExRate, idcostprice * ihExchangeRate, 'R',                                
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                
 -- -((idUnitPrice / reqqty) - idcostprice) margin,                                 
 -- -((idUnitPrice / reqqty) - idcostprice) *  ihDepExRate  dmargin ,                                 
 -- -((idUnitPrice / reqqty)  - idcostprice) *  ihExchangeRate cmargin,                                 
   
 -- -(idUnitPrice-idcostprice*reqqty) margin,                                 
 -- -(idUnitPrice-idcostprice*reqqty) *  ihDepExRate  dmargin ,                                 
 -- -(idUnitPrice-idcostprice*reqqty) *  ihExchangeRate cmargin,                                 
 -((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*reqqty) margin,                                 
 -((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*reqqty) *  ihDepExRate  dmargin ,                                 
 -((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*reqqty) *  ihExchangeRate cmargin,                                 
   
 --convert(numeric(18,8),-idUnitPrice) Amount,   
 --convert(numeric(18,8),-idUnitPrice * ihExchangeRate) cAmount,                                 
 --convert(numeric(18,8),-idUnitPrice * ihDepExRate) dAmount,          
 convert(numeric(18,8),-(idUnitPrice-isnull(idItemTaxAmount,0))) Amount,   
 convert(numeric(18,8),-(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) cAmount,                                 
 convert(numeric(18,8),-(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dAmount,          
  
 convert(numeric(18,8),-idActualUnitPrice * reqqty) ActualAmount,--sree          
 convert(numeric(18,8),-idActualUnitPrice * ihExchangeRate *reqqty) cActualAmount,  --sree                    
 convert(numeric(18,8),-idActualUnitPrice * ihDepExRate *reqqty) dActualAmount,     --sree         
 IhCustomerID,  
 convert(numeric(18,8),-(isnull(idItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),-(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,  
 convert(numeric(18,8),-(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount                               
from                                 
 losspecialinvoicedetail,losspecialinvoiceheader       
where                                 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1                                
                                 
union all                                
-- 7                                 
-- (- Qty has to be minus so when multiplying - * - =+ so i am removing the - on values )                                
--venkitesh 150403                                
--select                                 
-- grnditemid,          
-- convert(numeric(18,8),( GRNDUnitPrice / GRNDQuantity)  *  grnhExchangeRate) cUnitPrice,             
-- convert(numeric(18,8),( GRNDUnitPrice / GRNDQuantity)  *  grnhDepExRate) dUnitPrice,                                
-- convert(numeric(18,8),( GRNDUnitPrice / GRNDQuantity) ) UnitPrice,                                
-- -GRNDQuantity GRNDQuantity, 0 as ratetype,  GrnhGoodsreturnnoteDate , GrnhGoodsreturnnoteID,                                
-- GrnhGoodsreturnnoteNO, grnhShopid, grncostprice, grncostprice * grnhDepExRate,                                 
-- grncostprice * grnhExchangeRate, 'R' as type,                                 
-- -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                
-- -- ((GRNDUnitPrice / GRNDQuantity) - grncostprice) margin,                                 
-- -- ((GRNDUnitPrice / GRNDQuantity) - grncostprice) * grnhDepExRate dmargin,                                 
-- -- ((GRNDUnitPrice / GRNDQuantity) - grncostprice) *  grnhExchangeRate cmargin,                                
-- GRNDUnitPrice-grncostprice*GRNDQuantity margin,                                 
-- (GRNDUnitPrice-grncostprice*GRNDQuantity) * grnhDepExRate dmargin,               
-- (GRNDUnitPrice-grncostprice*GRNDQuantity) *  grnhExchangeRate cmargin,                                
-- convert(numeric(18,8),-grndUnitPrice) Amount,convert(numeric(18,8),-grndUnitPrice * grnhExchangeRate) cAmount,                                
-- convert(numeric(18,8),-grndUnitPrice * grnhDepExRate) dAmount                                
--from                                 
-- losgoodsreturnnoteheader, losgoodsreturnnotedetail                                 
--where                                  
-- GrnhGoodsreturnnoteID  =  GRNDReturnNoteID and                                 
-- grnhShopid =  GRNDShopid AND GrnhCancel = 0           
                                
--Sreejith Commented Above and rewritten below with joining losinvoicedetail to find the returned items Actual price          
          
select                                 
 grnditemid,          
 convert(numeric(18,8), idActualUnitPrice *  grnhExchangeRate) cActualUnitPrice,  --sree                     
 convert(numeric(18,8), idActualUnitPrice *  grnhDepExRate) dActualUnitPrice,   --sree              
 convert(numeric(18,8), idActualUnitPrice) ActualUnitPrice,  --sree          
  
 --convert(numeric(18,8),( -GRNDUnitPrice / CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END)  *  grnhExchangeRate) cUnitPrice,    --RefNo:1                              
 --convert(numeric(18,8),( -GRNDUnitPrice / CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END)  *  grnhDepExRate) dUnitPrice,        --RefNo:1                         
 --convert(numeric(18,8),( -GRNDUnitPrice / CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END) ) UnitPrice,                           --RefNo:1      
 convert(numeric(18,8),( -GRNDUnitPrice/CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END)-(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))  *  grnhExchangeRate) cUnitPrice,    --RefNo:1                              
 convert(numeric(18,8),( -GRNDUnitPrice/CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END)-(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))  *  grnhDepExRate) dUnitPrice,        --RefNo:1                         
 convert(numeric(18,8),( -GRNDUnitPrice/CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END)-(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)) ) UnitPrice,                           --RefNo:1      
  
 -GRNDQuantity GRNDQuantity, 0 as ratetype,  GrnhGoodsreturnnoteDate , GrnhGoodsreturnnoteID,                                
 GrnhGoodsreturnnoteNO, grnhShopid, grncostprice, grncostprice * grnhDepExRate,                                 
 grncostprice * grnhExchangeRate, 'R' as type,                                 
  
 --GRNDUnitPrice-grncostprice*GRNDQuantity margin,                                 
 --(GRNDUnitPrice-grncostprice*GRNDQuantity) * grnhDepExRate dmargin,                                 
 --(GRNDUnitPrice-grncostprice*GRNDQuantity) *  grnhExchangeRate cmargin,                                
 (GRNDUnitPrice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))-grncostprice*GRNDQuantity margin,                                 
((GRNDUnitPrice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))-grncostprice*GRNDQuantity) * grnhDepExRate dmargin,                                 
((GRNDUnitPrice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))-grncostprice*GRNDQuantity) *  grnhExchangeRate cmargin,                                
  
 --convert(numeric(18,8),-grndUnitPrice) Amount,  
 --convert(numeric(18,8),-grndUnitPrice * grnhExchangeRate) cAmount,                                
 --convert(numeric(18,8),-grndUnitPrice * grnhDepExRate) dAmount,          
 convert(numeric(18,8),-(grndUnitPrice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))) Amount,  
 convert(numeric(18,8),-(grndUnitPrice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)) * grnhExchangeRate) cAmount,                                
 convert(numeric(18,8),-(grndUnitPrice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)) * grnhDepExRate) dAmount,          
   
 convert(numeric(18,8),-idActualUnitPrice * GRNDQuantity) ActualAmount,--sree          
 convert(numeric(18,8),-idActualUnitPrice * grnhExchangeRate *GRNDQuantity) cActualAmount,  --sree                    
 convert(numeric(18,8),-idActualUnitPrice * grnhDepExRate *GRNDQuantity) dActualAmount,     --sree        
 GrnhCustomerID,  
-convert(numeric(18,8),-(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))GSTAmount  
,-convert(numeric(18,8),-(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,  
-convert(numeric(18,8),-(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhexchangerate)cGSTAmount  
                                  
from                                 
 losgoodsreturnnotedetail           
left outer join  losgoodsreturnnoteheader on  GrnhGoodsreturnnoteID  =  GRNDReturnNoteID and                                 
 grnhShopid =  GRNDShopid           
left outer join losinvoicedetail  on idShopID= GRNDShopid  and idInvoiceID=GrnhInvoiceID          
and GRNDItemID=idItemID                                
where  GrnhCancel = 0           
                                
UNION ALL                                
-- 8            
select                                 
 repinvdpartsid,          
 convert(numeric(18,8), repinvdsellrate *  serinvhcmpexrate) cActualUnitPrice,  --sree                     
 convert(numeric(18,8), repinvdsellrate *  seinvhDepExRate) dActualUnitPrice,   --sree              
 convert(numeric(18,8), repinvdsellrate) ActualUnitPrice,  --sree          
   
 --convert(numeric(18,8) , repinvdrate  *  serinvhcmpexrate) cUnitPrice,                                 
 --convert(numeric(18,8) , repinvdrate  *  seinvhDepExRate) dUnitPrice,                           
 --convert(numeric(18,8) , repinvdrate ) UnitPrice,  
 convert(numeric(18,8) , (repinvdrate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty))  *  serinvhcmpexrate) cUnitPrice,                           
 convert(numeric(18,8) , (repinvdrate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty))  *  seinvhDepExRate) dUnitPrice,                           
 convert(numeric(18,8) , (repinvdrate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty))) UnitPrice,  
   
 repinvdqty, 0 as ratetype, serinvhdate ,                                 
 serinvhid , serinvNo , serinvhShopid, repinvdcostprice, repinvdcostprice *  seinvhDepExRate,                                 
 repinvdcostprice * serinvhcmpexrate, 'b',                                 
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                
 -- (repinvdrate - repinvdcostprice) margin,                                
 -- (repinvdrate - repinvdcostprice) *  seinvhDepExRate dmargin,                                 
 -- (repinvdrate  - repinvdcostprice) *  serinvhcmpexrate cmargin,                                
   
 --(repinvdrate - repinvdcostprice*repinvdqty) margin,                                
 --(repinvdrate - repinvdcostprice*repinvdqty) *  seinvhDepExRate dmargin,                                 
 --(repinvdrate - repinvdcostprice*repinvdqty) *  serinvhcmpexrate cmargin,                                
 ((repinvdrate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty)) - repinvdcostprice*repinvdqty) margin,                                
 ((repinvdrate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty)) - repinvdcostprice*repinvdqty) *  seinvhDepExRate dmargin,                                 
 ((repinvdrate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty)) - repinvdcostprice*repinvdqty) *  serinvhcmpexrate cmargin,                                
   
 --convert(numeric(18,8),RepInvDRate * repinvpackqty) Amount,                                
 --convert(numeric(18,8),RepInvDRate * ISNULL(serinvhcmpexrate, 1) * repinvpackqty) cAmount,                                
 --convert(numeric(18,8),RepInvDRate * ISNULL(seinvhDepExRate, 1) * repinvpackqty) dAmount,  
 convert(numeric(18,8),(RepInvDRate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty)) * repinvpackqty) Amount,                                
 convert(numeric(18,8),(RepInvDRate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty)) * ISNULL(serinvhcmpexrate, 1) * repinvpackqty) cAmount,                                
 convert(numeric(18,8),(RepInvDRate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty)) * ISNULL(seinvhDepExRate, 1) * repinvpackqty) dAmount,         
          
 convert(numeric(18,8),repinvdsellrate * repinvdqty) ActualAmount,--sree          
 convert(numeric(18,8),repinvdsellrate * serinvhcmpexrate *repinvdqty) cActualAmount,  --sree                    
 convert(numeric(18,8),repinvdsellrate * seinvhDepExRate *repinvdqty) dActualAmount ,    --sree          
serinvhCustomerId,  
 convert(numeric(18,8),(isnull(repinvdItemTaxAmount,0)))GSTAmount  
,convert(numeric(18,8),(isnull(repinvdItemTaxAmount,0))* seinvhDepExRate)dGSTAmount,  
 convert(numeric(18,8),(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount                               
from                                 
 losinvoicedpartsreplacedetails, losserviceinvheader                                 
where                                 
 serinvhid  =  repinvinvoiceid  and serinvhshopid  =  repinvdshopid AND                                 
 serinvhcancelled = 0                                 
                                
union all                                
-- 9                                
select                                 
 reditemid,           
 convert(numeric(18,8), redActualUnitPrice *  rehExchangeRate) cActualUnitPrice,  --sree                     
 convert(numeric(18,8), redActualUnitPrice *  rehDepExRate) dActualUnitPrice,   --sree              
 convert(numeric(18,8), redActualUnitPrice) ActualUnitPrice,  --sree          
 convert(numeric(18,8),                                 
 (redUnitPrice / CASE WHEN redquantity=0 THEN 1 ELSE redquantity END) * rehExchangeRate) cUnitPrice,                       --RefNo:1           
 convert(numeric(18,8), (redUnitPrice / CASE WHEN redquantity=0 THEN 1 ELSE redquantity END)  *  rehDepExRate) dUnitPrice, --RefNo:1                    
 convert(numeric(18,8), (redUnitPrice / CASE WHEN redquantity=0 THEN 1 ELSE redquantity END)) posdUnitPrice,               --RefNo:1                   
 redquantity, redRateType, rehExportDate, rehExportID, rehExportNo, rehShopid, redcostprice,                                 
 redcostprice * rehDepExRate, redcostprice * rehExchangeRate, 'S',                                
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                
 -- ((redUnitPrice / redquantity) * rehExchangeRate - redcostprice) margin,                                 
 -- ((redUnitPrice / redquantity) - redcostprice) * rehDepExRate  dmargin,                                
 -- ((redUnitPrice / redquantity) - redcostprice) * rehExchangeRate cmargin,   
 redUnitPrice - redcostprice*redquantity margin,                                 
 (redUnitPrice - redcostprice*redquantity) * rehDepExRate  dmargin,                                
 (redUnitPrice - redcostprice*redquantity) * rehExchangeRate cmargin,                                
 convert(numeric(18,8),redUnitPrice) Amount,convert(numeric(18,8),redUnitPrice * rehExchangeRate) cAmount,                                
 convert(numeric(18,8),redUnitPrice * rehDepExRate) Amount,          
 convert(numeric(18,8),redActualUnitPrice * redquantity) ActualAmount,--sree          
 convert(numeric(18,8),redActualUnitPrice * rehExchangeRate *redquantity) cActualAmount,  --sree                    
 convert(numeric(18,8),redActualUnitPrice * rehDepExRate *redquantity) dActualAmount,     --sree        
rehcustomerid,  
0,0,0                                 
from                                 
 losExportDetail, losExportHeader                                
where                                 
 rehExportID = redExportID and rehShopID = redShopID AND                                 
 rehCancelled = 0 and rehproforma = 0 and rehtype = 'i'   
 
 
 GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:New Report -  Sales/Import Analysis GST Seprately (Advanced)working script got from bijesh on 04.10.2012 
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwPurchaseBillDetailGSTSeparately')
   DROP view dbo.vwPurchaseBillDetailGSTSeparately  
GO
/****** Object:  View dbo.vwPurchaseBillDetail    Script Date: 18/01/2003 9:45:37 PM ******/          
--modified By : Hariharan          
--Modified On : 08/01/2003          
--Modified On : 17/06/2006         
--modified By : aneesh [removed text in convert function and added varchar]          
  
-- modified by : Bijesh.B  
-- date        : 07/10/2011  
-- des         : null handled for quantity, cdcostingprice and cdOldItemCostPrice  
---------------------------------------------------------------------------------------------------------------

-- Created by : Aadyakumar.D.V.  
-- date        : 07/10/2011  
-- des         : Created from vwPurchaseBillDetail
  ---------------------------------------------------------------------------------------------   
  
create   view  dbo.vwPurchaseBillDetailGSTSeparately           
as          
--hari altered to handle the costing with out custom duty - 020805           
select ph.pbhbilldate, pb.*,uom.unitcode,pt.packingtypecode,uom.unitid,  
isnull(ptc.quantity,0)quantity,          
convert(varchar(250),vw.itemdescription) itemdescription, cstm.customcategorypercent,           
isnull(icp.cdcostingprice,0)cdcostingprice,icp.symbol, isnull(custom.cadamount,0) cadamount,       
isnull( oc.otherc,0) otherc, isnull(icp.cdnewitemcostprice,0)cdnewitemcostprice,           
isnull(icp.cdOldItemCostPrice,0)cdOldItemCostPrice
 from aunit uom, apackingtype pt,  
apackingtypecapacitydetail ptc,           
vwitemdescription vw, acustomsmaster cstm, (select ch.chbillid, cd.cdItemID,           
cd.cdCostingPrice, cur.symbol, cd.cdOldItemCostPrice,cd.cdnewitemcostprice  from           
loacostingheader ch, loacostingdetail cd,acompanymaster com, acurrencymaster cur          
 where com.companyid = cur.companyid and com.currencyid = cur.currencyid and           
ch.chcompanyid = com.companyid and ch.chcostingid = cd.cdcostingid           
and ch.chcancelled = 0 ) icp , losppurchasebillheader ph left outer join (select ch.chbillid,           
isnull(cadamount,0) cadamount from loacostingaccountdetails cad, loacostingheader ch, apackagesettings where             
ch.chcostingid = cad.cadcostingid and ch.chcancelled = 0 and cad.cadaccountid=customsaccid          
and caddetailid=1)           
custom on custom.chbillid = pbhbillid            
, LOspPurchaseBillDetail pb   
left outer join (select ch.chbillid, isnull(sum(isnull(cadamount,0)),0) otherc           
from loacostingaccountdetails cad, loacostingheader ch, apackagesettings where             
ch.chcostingid = cad.cadcostingid and ch.chcancelled = 0 and cadaccountid<>customsaccid           
group by ch.chbillid ) oc on oc.chbillid = pb.pbdbillid         
left outer join  aitem ai on pbdItemID=ItemID           
where ph.pbhbillid = pb.pbdbillid and           
icp.cditemid = pb.pbditemid and icp.chbillid = pb.pbdbillid and          
 cstm.customid = ai.customid and vw.itemid = ai.itemid and           
pt.packingtypeid = pb.pbdpackingtypeid and  ptc.packingtypeid = pb.pbdpackingtypeid          
and ptc.unitsid = uom.unitid and uom.unitid = ai.unitsid        
      
GO

------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:New Report -  Sales/Import Analysis GST Seprately (Advanced)working script got from bijesh on 04.10.2012 
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
  
GO
IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwSalesMarginAndPercGSTSeparately')
   DROP view dbo.vwSalesMarginAndPercGSTSeparately
GO
  
-- Modified on          : 12/12/02        
-- Modified by   : leo        
-- Comments  : v3        
----------------------------------------------------------------------------------------        
-- Modified on          : 12/06/2003        
-- Modified by          : Kishore        
-- Comments             : Added amount column        
--                        Added cAmount and dAmount on 18/06/2003        
-- Sebin(24/06/09)-Changed itemunitprice,ditemunitprice & citemUnitPrice,it was taken average before                      
----------------------------------------------------------------------------------------       
-- Modified on  :-12-08-09    
-- Modified by  :Nidheesh     
--Comments :to avoid Divide by zero error 'itemunitprice'is diredctly taken from view vs    
--comments  :included the condition avg(posdunitprice)in MARGIN and PERCENTAGE to consider RBD    
----------------------------------------------------------------------------------------    
--This view is created from vwSalesMarginAndPerc for hadling gst sepepratly
--crated on 07/05/2012
--Created by Aadyakumar.D.V
----------------------------------------------------------------------------------------------------------------------
create VIEW vwSalesMarginAndPercGSTSeparately  AS        
select ic.categorynamedescription, a.itemcode, a.brand, a.modelno, vd.itemdescription,         
posditemid, a.itemcategoryid,       
--sum(amount)/sum(posdquantity)itemunitprice     
vs.posdUnitPrice itemunitprice,     
--sum(dAmount)/sum(posdquantity) ditemunitprice,    
vs.dUnitPrice ditemunitprice,     
--sum(cAmount)/sum(posdquantity) citemunitprice,    
vs.cUnitPrice citemunitprice,          
sum(posdquantity) quantity, poshBilldate, poshShopID,         
AVG(costprice) costprice, AVG(dcostprice) dcostprice, AVG(ccostprice) ccostprice,     
    
--(avg(posdunitprice) - AVG(costprice))Margin        
case when avg(posdunitprice)=0 then -(avg(posdunitprice) - AVG(costprice))else(avg(posdunitprice) - AVG(costprice))end Margin,      
--(avg(dunitprice) - AVG(dcostprice)) dMargin,    
case when avg(posdunitprice)=0 then -(avg(dunitprice) - AVG(dcostprice))else(avg(dunitprice) - AVG(dcostprice))end dMargin,            
--(avg(cunitprice) - AVG(ccostprice)) cMargin,          
case when avg(posdunitprice)=0 then -(avg(cunitprice) - AVG(ccostprice))else(avg(cunitprice) - AVG(ccostprice))end cMargin,            
    
--case when avg(costprice)>0 then (avg(posdunitprice) - AVG(costprice))/AVG(costprice)         
--else (avg(posdunitprice) - AVG(costprice)) end Percentage,         
--case when avg(dcostprice)>0 then (avg(dunitprice) - AVG(dcostprice))/AVG(dcostprice)         
--else (avg(dunitprice) - AVG(dcostprice)) end dPercentage,        
--case when avg(ccostprice)>0 then (avg(cunitprice) - AVG(ccostprice))/AVG(ccostprice)         
--else (avg(cunitprice) - AVG(ccostprice)) end cPercentage,       
case when avg(costprice)<>0 then case when avg(posdunitprice)=0 then -(avg(posdunitprice) - AVG(costprice))/AVG(costprice)    
else (avg(posdunitprice) - AVG(costprice))/AVG(costprice)end        
else (avg(posdunitprice) - AVG(costprice)) end Percentage,         
case when avg(dcostprice)<>0 then case when avg(posdunitprice)=0 then -(avg(dunitprice) - AVG(dcostprice))/AVG(dcostprice)    
else (avg(dunitprice) - AVG(dcostprice))/AVG(dcostprice)end             
else (avg(dunitprice) - AVG(dcostprice)) end dPercentage,        
case when avg(ccostprice)<>0 then case when avg(posdunitprice)=0  then -(avg(cunitprice) - AVG(ccostprice))/AVG(ccostprice)        
else (avg(cunitprice) - AVG(ccostprice))/AVG(ccostprice)end         
else (avg(cunitprice) - AVG(ccostprice)) end cPercentage,       
sum(amount) Amount, sum(dAmount) dAmount, sum(cAmount) cAmount,   
sum(GSTAmount) GST, sum(dGSTAmount) dGST, sum(cGSTAmount) cGST        
from vwShopItemSalesGSTSeparately vs, aitem a, vwitemdescription vd,        
aitemcategory ic where vs.posditemid=a.itemid and a.itemid=vd.itemid and        
a.itemcategoryid= ic.itemcategoryid group by poshBilldate, poshshopid,         
posditemid, a.itemcategoryid, poshBilldate, ic.categorynamedescription,         
a.itemcode, a.brand, a.modelno,vd.itemdescription,vs.posdUnitPrice,vs.dUnitPrice,vs.cUnitPrice       
  


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:New Report -  Sales/Import Analysis GST Seprately (Advanced)working script got from bijesh on 04.10.2012 
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwSalesImportProdWiseGSTSeparately')
   DROP view dbo.vwSalesImportProdWiseGSTSeparately
GO

-- Last Modified by : Kishore, Hariharan , Hariharan R    
-- Modified on      : 09/05/2003, 14/05/2003, 06/06/2003    
-- Comments         : Added sales date column and removed grouping by    
--                    Month and year (08/03/2003)    
--                    Replaced view vwImportQty with vwPurchaseBillDetail (18/03/2003)    
--      : Given convert function to take the numeric values       
-----------------------------------------------------------------    
-- Replaced with source from v2 on 12/06/2003    
-----------------------------------------------------------------    
-- Modified on      : 18/06/2003    
-- Modified by      : Kishore    
-- Comment          : Added MonthName, MonthNo, YearName columns and other columns    
  
--Modified on       :12-08-09  
--Modified By       :Nidheesh   
--comment           :considered 'Percentage' as negative for RBD case   
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--This View is Created from vwSalesImportProdWise for handling GST seperately
--Created by:Aadyakumar.D.V
--Dated:07/05/2012
----------------------------------------------------------------
  
  --Modified by : Bijesh.B
--Date        : 04-10-2012
--Des         : Bug Fixing-Dept wise GST
----------------------------------------------------------------

create VIEW vwSalesImportProdWiseGSTSeparately AS    
    
	SELECT c.CategoryNameDescription, i.ItemCode, i.ItemDescription,     
	Margin.ItemId, i.ItemCategoryId,    
	AVG(Margin.ItemUnitPrice) ItemUnitPrice,     
	AVG(Margin.dItemUnitPrice) dItemUnitPrice,     
	AVG(Margin.cItemUnitPrice) cItemUnitPrice,     
	CONVERT(numeric(18,3), SUM(ISNULL(Margin.Quantity, 0))) Quantity,     
	CONVERT(numeric(18,2), sum(Costprice)) CostPrice,     
	CONVERT(numeric(18,2), sum(dCostprice)) dCostPrice,     
	CONVERT(numeric(18,2), sum(cCostprice)) cCostPrice,     
	CONVERT(numeric(18,2), SUM(Margin.Margin)) Margin,     
	CONVERT(numeric(18,2), SUM(Margin.dMargin)) dMargin,     
	CONVERT(numeric(18,2), SUM(Margin.cMargin)) cMargin,     
	--convert(numeric(18,2),(SUM(Margin.Margin) * 100) / sum(Costprice) ) Percentage,    
	--SUM(Percentage) Percentage,  
	case when Quantity>0 then SUM(Percentage)else -SUM(Percentage)end Percentage,    
	--SUM(dPercentage) dPercentage,  
	case when Quantity>0 then SUM(dPercentage)else -SUM(dPercentage)end dPercentage,      
	--SUM(cPercentage) cPercentage,  
	case when Quantity>0 then SUM(cPercentage)else -SUM(cPercentage)end cPercentage,        
	CONVERT(numeric(18,3), SUM(ISNULL(Margin.TransQty, 0))) TransQty,    
	SalesDate, sum(Amount) Amount, margin.MonthName, margin.MonthNo, margin.YearName ,
	sum(GST)GST, --aadya    
	sum(dGST)dGST,
	sum(cGST)cGST
	FROM    
	 (SELECT posdItemId ItemId,    
	 ItemUnitPrice, dItemUnitPrice, cItemUnitPrice,    
	 Quantity, 0 TransQty, poshBilldate SalesDate,     
	 Margin, dMargin, cMargin,    
	 Amount, dAmount, cAmount,    
	 costprice, dCostPrice, cCostPrice,    
	 substring(convert(varchar(4), datename(month, poshbilldate)),1,3) MonthName,     
	 month(poshbilldate) MonthNo,     
	 year(poshbilldate) YearName,    
	 Percentage, dPercentage, cPercentage,
	 isnull(GST,0)GST,  --aadya    
	 isnull(dGST,0)dGST,
	 isnull(cGST,0)cGST
	 FROM vwSalesMarginAndPercGSTSeparately mp    
		 
	 UNION ALL    
 
	 SELECT pbdItemId ItemId,     
	 pbdItemUnitPrice, 
	 pbdItemUnitPrice dUnitPrice, 
	 pbdItemUnitPrice cUnitPrice,    
	 0 Quantity, pbdItemQuantity TransQty, pbhBilldate SalesDate,     
	 0 Margin, 0 dMargin, 0 cMargin,    
	 0 amount, 0 dAmount, 0 cAmount,    
	 0 costprice, 0 dCostPrice, 0 cCostPrice,    
	 substring(convert(varchar(4), datename(month, pbhBilldate)), 1, 3) MonthName,     
	 month(pbhBillDate) MonthNo,     
	 year(pbhBillDate) YearName,    
	 0 Percentage, 0 dPercentage, 0 cPercentage 
	 ,isnull(pbdItemTaxAmount,0) gst --aadya   
	 ,isnull(pbdItemTaxAmount,0) dgst
	 ,isnull(pbdItemTaxAmount,0) cgst
	 FROM vwPurchaseBillDetailGSTSeparately iq) Margin, aItem i, aItemCategory c    
	WHERE Margin.ItemId = i.ItemId    
	AND i.ItemCategoryId = c.ItemCategoryId    
	GROUP BY c.CategoryNameDescription, i.ItemCode, i.ItemDescription,     
	Margin.ItemId, i.ItemCategoryId, CostPrice, Margin.SalesDate,     
	margin.yearname, margin.monthname, margin.monthno,Margin.Quantity    
    
 GO

------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Working of New Report -  Sales and Collection Detailed with GST Separately got from bijesh on 05.09.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwPosExchangeDetailsGSTSepartely')
   DROP view dbo.vwPosExchangeDetailsGSTSepartely
GO

--Created by : Bijesh.B
--Date       : 05-10-2012
--------------------------------------------------------------------

create View vwPosExchangeDetailsGSTSepartely As

Select sehexchangeid,sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,       
    COnvert(numeric(18,8),Sum(sedunitprice-isnull(sedItemTaxAmount,0))) As amount,      
    COnvert(numeric(18,8),Sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehdepexrate) As damount,      
    COnvert(numeric(18,8),Sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehexchangerate) As camount,      
    1 cash,'c'  As transtype, sehdepartmentid departmentid
    ,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
	convert(numeric(18,8),sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount      
From  losposexchangeheader ph, losposexchangedetail pd       
Where ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid And       
    sehcancelled=0 And sedbillorexchange ='E'     
Group By sehcompanyid,sehshopid, sehexchangedate, sehexchangeid,    
    sehcAshaccid, sehdepartmentid, sehdepexrate, sehexchangerate    
   
    
UniOn All      
      
Select sehexchangeid,sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,       
    COnvert(numeric(18,8),-Sum(sedunitprice-isnull(sedItemTaxAmount,0))) As amount,       
    COnvert(numeric(18,8),-Sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehdepexrate) As damount,      
    COnvert(numeric(18,8),-Sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehexchangerate) As camount,
    1,'c' As transtype, sehdepartmentid  departmentid 
	,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
	convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount      
     
From   losposexchangeheader ph, losposexchangedetail pd ,LOsPosHeader posh     
Where ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid       
    And sehcancelled=0 And sedbillorexchange ='B' 
    And sedexchangeqty > 0      
    and posh.poshBillID=ph.sehBillID  and posh.poshShopID= ph.sehShopID 
	and  isnull(posh.PosPostDate,0)=0
Group By sehcompanyid, sehshopid, sehexchangedate, sehexchangeid, sehcAshaccid,       
    sehdepartmentid, sehdepexrate, sehexchangerate      
   
UniOn All      
--PD CHEQUE      
Select sehexchangeid,sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,       
    COnvert(numeric(18,8),-Sum(sedunitprice-isnull(sedItemTaxAmount,0))) As amount,       
    COnvert(numeric(18,8),-Sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehdepexrate) As damount,      
    COnvert(numeric(18,8),-Sum(sedunitprice-isnull(sedItemTaxAmount,0)) * sehexchangerate) As camount,
    0,'PD CHEQUE' As transtype, sehdepartmentid  departmentid 
	,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,
	convert(numeric(18,8),-sum(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount      
     
From   losposexchangeheader ph, losposexchangedetail pd ,LOsPosHeader posh     
Where ph.sehshopid = pd. sedshopid And ph.sehexchangeid = pd.sedexchangeid       
    And sehcancelled=0 And sedbillorexchange ='B' 
    And sedexchangeqty > 0      
    and posh.poshBillID=ph.sehBillID  and posh.poshShopID= ph.sehShopID 
	and  isnull(posh.PosPostDate,0)=1
Group By sehcompanyid, sehshopid, sehexchangedate, sehexchangeid, sehcAshaccid,       
    sehdepartmentid, sehdepexrate, sehexchangerate      
   
GO

------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Working of New Report -  Sales and Collection Detailed with GST Separately got from bijesh on 05.09.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwCAshSalesDetGSTSeprately')
   DROP view dbo.vwCAshSalesDetGSTSeprately
GO
--  vwCAshSalesDetGSTSeprately
--  Created by Bijesh.B
--  Date : 05-10-2012
--  Desc : For report-> rptdailysalescollectionshopwisedetgstseparately
--                      rptdailysalescollectiondepwisedetgstseparately  
---------------------------------------------------------------------------------
 
create View [dbo].[vwCAshSalesDetGSTSeprately] As    
	Select poshcompanyid As companyid, poshshopid As shopid, poshbilldate As billdate,       
	poshcAshaccid As accountid,
	convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) amount, 
	convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) damount,
	convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) camount,
	1 As cAsh, 'p' As transtype, poshdepartmentid departmentid 
	,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,
	convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,
	convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount
     
	From  losposheader ph,losposdetail pd   Where       
	ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0       
	and isnull(ph.PosPostDate,0)<>1 --RefNo-1
	Group By poshcompanyid , poshshopid , poshbilldate ,poshbillid, poshcAshaccid ,       
	poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate      
    
--RefNo-1 start ---------------------------
  union all
	Select poshcompanyid As companyid, poshshopid As shopid, poshbilldate As billdate,       
	poshcAshaccid As accountid,
	convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0))) amount, 
	convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshdepexrate) damount,
	convert(numeric(18,8),sum(posdunitprice-isnull(posdItemTaxAmount,0)) * poshexchangerate) camount,
	0 As cAsh, 'PD CHEQUE' As transtype, poshdepartmentid departmentid 
	,convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0)))GSTAmount,
	convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,
	convert(numeric(18,8),sum(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount
     
	From  losposheader ph,losposdetail pd   Where       
	ph.poshshopid = pd.posdshopid And ph.poshbillid = pd.posdbillid And ph.poshcancelled=0       
	and isnull(ph.PosPostDate,0)=1 --RefNo-1
	Group By poshcompanyid , poshshopid , poshbilldate ,poshbillid, poshcAshaccid ,       
	poshdepartmentid, poshbillamount,poshdepexrate, poshexchangerate      

    UniOn All  
    
    Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,       
    COnvert(numeric(18,8),Sum(amount)) As amount,      
    COnvert(numeric(18,8),Sum(damount)) As damount,      
    COnvert(numeric(18,8),Sum(camount)) As camount,      
    1,'E' As transtype, departmentid departmentid      
    , GSTAmount,dGSTAmount,cGSTAmount
    From  vwPosExchangeDetailsGSTSepartely
    Group By sehcompanyid,sehshopid, sehexchangedate,sehexchangeid ,   
    sehcAshaccid,departmentid,GSTAmount,dGSTAmount,cGSTAmount
    Having Sum(amount)<0

--bb s
-- Goods exchange tax only
UniOn All  
    
    Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,       
    0 As amount,      
    0 As damount,      
    0 As camount,      
    1,'p' As transtype, departmentid departmentid      
    , GSTAmount,dGSTAmount,cGSTAmount
    From  vwPosExchangeDetailsGSTSepartely
    Group By sehcompanyid,sehshopid, sehexchangedate,sehexchangeid ,   
    sehcAshaccid,departmentid,GSTAmount,dGSTAmount,cGSTAmount
    Having Sum(amount)<0

union all
--Goods Return tax only
 Select GrnCompanyID, grnhshopid, grnhGoodsReturnNoteDate, grnhCustomerId,       
   0 amount,                 
   0 damount,                 
   0 camount, 
    0, 'p' As transtype, Grnhdepartmentid  departmentid       
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,
    -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount

    From losGoodsReturnNoteHeader ih, losGoodsReturnNoteDetail invd     
    Where ih.GrnhShopid = invd.grndshopid And ih.GrnhGoodsreturnnoteID = invd.GrndreturnnoteID      
    And grnhCancel = 0  Group By grncompanyid, grnhshopid, grnhGoodsReturnNoteDate,       
    GrnhGoodsreturnnoteID, grnhCustomerID, grnhdepartmentid, grnhdepExRate, grnhExchangeRate      
  

--bb e
    UniOn All      
      
     Select sehcompanyid, sehshopid, sehexchangedate, sehcAshaccid,       
    COnvert(numeric(18,8),Sum(amount)) As amount,      
    COnvert(numeric(18,8),Sum(damount)) As damount,      
    COnvert(numeric(18,8),Sum(camount)) As camount,      
    1,'c'  As transtype, departmentid departmentid 
    ,GSTAmount,dGSTAmount,cGSTAmount     
    From  vwPosExchangeDetailsGSTSepartely
    Group By sehcompanyid,sehshopid, sehexchangedate,sehexchangeid,    
    sehcAshaccid,departmentid,GSTAmount,dGSTAmount,cGSTAmount
    Having Sum(amount)>0 

	
    UniOn All      
      
    Select ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,       
    Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
    (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0))     
    Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))  End Amount,       
    Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
    (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0)) * ihdepexrate    
    Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))* ihdepexrate  End DAmount,       
    Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
    (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+Isnull(ocd.ioAmount,0)) * ihExchangeRate     
    Else (Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))+ Isnull(ocd.ioAmount,0))* ihExchangeRate End cAmount,     
    1,'c' As transtype, ih.ihdepartmentid  departmentid
	,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount,
	convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount
       
    From  losinvoiceheader ih Left Outer Join losinvoicedetail invd On ih.ihshopid = invd.idshopid      
    And ih.ihinvoiceid = invd.idinvoiceid  Left Outer Join      
    (Select ioShopID,ioInvoiceID,Sum(ioAmount) ioAmount From losInvoiceOC       
    Group By   ioShopID,ioInvoiceID) ocd  On ihshopid= ocd.ioShopid And     
    ihinvoiceid=ocd.ioInvoiceID, Ashops s   Where       
    ihcancelled=0 And ihcAshinvoice = 1 And ih.ihproforma =0 And ih.ihtype='I'      
     And ihshopid = s.shopid And ihcompanyid = s.COmpanyid      
    Group By ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid,     
    ihdepartmentid,  ihdepexrate, ihexchangerate, ocd.ioAmount, s.futurevarchar, ih.ihdutypaidby      
      
    Union All      

--RefNo-3 start 
-- commented below 
/*
      
Select       
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,       
 COnvert(numeric(18,8),Sum( vw.idunitprice ))  As amount,      
 COnvert(numeric(18,8),Sum( vw.idunitprice) * ihdepexrate)  As damount,      
 COnvert(numeric(18,8),Sum( vw.idunitprice) * ihexchangerate)  As camount,      
 1, 'd' As transtype, ihdepartmentid departmentid       
From       
 losspecialinvoiceheader ih, vwShopSplInvItemAmount vw       
Where       
 ih.ihshopid = vw.idshopid And ih.ihinvoiceid = vw.idinvoiceid And       
 ihcancelled=0 And ihcAshinvoice =1 And ih.ihproforma =0 And ihtransfinIshed=1      
Group By    
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,       
 ihdepexrate, ihexchangerate      
      
UniOn All      

     
--direct invoice      
Select       
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,       
 COnvert(numeric(18,8),Sum(idunitprice) ) As amount,       
 COnvert(numeric(18,8),Sum(idunitprice) * ihdepexrate) As damount,       
 COnvert(numeric(18,8),Sum(idunitprice) * ihexchangerate) As camount,       
 0 ihcAshinvoice, 'd' As transtype, ihdepartmentid departmentid       
From       
 losspecialinvoiceheader ih, vwShopSplInvItemAmount invd       
Where       
 ih.ihshopid = invd. idshopid And ih.ihinvoiceid = invd.idinvoiceid And       
 ihcancelled=0 And ihcAshinvoice =0 And ih.ihproforma =0 And ihTransfinIshed =1      
Group By    
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,       
 ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate  
*/

-- special Invoice (cash)  
select                                 
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,           
 --convert(numeric(18,8),sum(idUnitPrice)) amount,
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) damount,
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) camount,                                 
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0))) amount,
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) damount,
convert(numeric(18,8),sum(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) camount, 
 1, 'd' As transtype, ihdepartmentid departmentid
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
 
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader                                 
where                                 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                              
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                
 and IhTransFinished = 1 And ihcAshinvoice =1 and ihNoofOCDetails=0                            
Group By  
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                             
union all                                

-- special invoice - return before despatch                    
select       
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,     
--convert(numeric(18,8),-sum(idUnitPrice)) amount,
--convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) damount,
--convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) camount,                                 
convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) damount,    
convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) camount,     

1, 'd' As transtype, ihdepartmentid departmentid  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount

from                                 
 losspecialinvoicedetail,losspecialinvoiceheader                                
where 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice =1 and ihTransFinished = 1 
 and ihNoofOCDetails<>0                            
Group By  
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                                    
union all                                
                             
-- Special invoice return  - after desp                              
select                                 
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
 --convert(numeric(18,8),-sum(idUnitPrice)) amount,
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) damount, 
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) camount,                                 
convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) damount,    
convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) camount,   
 1, 'd' As transtype, ihdepartmentid departmentid  
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount

from                                 
 losspecialinvoicedetail,losspecialinvoiceheader                                
where          
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice =1                               
Group By  
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate

-- special Invoice (credit)
union all

select                                 
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,           
 --convert(numeric(18,8),sum(idUnitPrice)) amount,
 --convert(numeric(18,8),sum(idUnitPrice * ihDepExRate)) damount,
 --convert(numeric(18,8),sum(idUnitPrice * ihExchangeRate)) camount,                                 
	convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
	convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) damount,    
	convert(numeric(18,8),sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) camount,  
 0 ihcAshinvoice, 'd' As transtype, ihdepartmentid departmentid     
	,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
	convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
from                                 
 losspecialinvoicedetail, losspecialinvoiceheader                                 
where                                 
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                     
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0   
 and IhTransFinished = 1 And ihcAshinvoice<>1 and ihNoofOCDetails=0                            
Group By  
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                             
union all                                

-- special invoice - return before despatch                    
select       
ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,     
--convert(numeric(18,8),-sum(idUnitPrice)) amount,
--convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) damount,
--convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) camount,  
	 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
	 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate) damount,    
	 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate) camount,   
                               
0 ihcAshinvoice, 'd' As transtype, ihdepartmentid departmentid   
	 ,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
	 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount
 
from                                 
 losspecialinvoicedetail,losspecialinvoiceheader                                
where      
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 0 and ihproforma = 0  And ihcAshinvoice<>1 and ihTransFinished = 1 
 and ihNoofOCDetails<>0                            
Group By  
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
                                    
union all                                
                             
-- Special invoice return  - after desp                              
select                                 
 ihcompanyid, ihshopid, ihinvoicedate, ihbankcAshaccid,
 --convert(numeric(18,8),-sum(idUnitPrice)) amount,
 --convert(numeric(18,8),-sum(idUnitPrice * ihDepExRate)) damount, 
 --convert(numeric(18,8),-sum(idUnitPrice * ihExchangeRate)) camount,                                 
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0)))) amount,    
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihDepExRate)damount,    
 convert(numeric(18,8),-sum((idUnitPrice-isnull(idItemTaxAmount,0))) * ihExchangeRate)camount,     

 0 ihcAshinvoice, 'd' As transtype, ihdepartmentid departmentid 
	,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0)))GSTAmount
	,convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,
	 convert(numeric(18,8),-sum(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount

from                                 
 losspecialinvoicedetail,losspecialinvoiceheader                                
where          
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                 
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1 And ihcAshinvoice<>1                               
Group By  
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihbankcAshaccid, ihdepartmentid,     
 ihdepexrate, ihexchangerate
--RefNo-3 ends 

union all
      
Select       
 vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,       
 --COnvert(numeric(18,8),(vws.siamount )) As amount,       
 --COnvert(numeric(18,8),(vws.siamount * aidepexrate)) As damount,      
 --COnvert(numeric(18,8),(vws.siamount * aiexchangerate)) As camount,      
 	convert(numeric(18,8),(vws.siamount))as amount,   
	convert(numeric(18,8),(vws.sidamount))as  damount,
	convert(numeric(18,8),(vws.sicamount))as camount, 

 lah.aicAshinvoice , 's' As transtype, aidepartmentid departmentid  
	, (vws.GSTAmount)as GSTAmount
	, (vws.dGSTAmount)as dGSTAmount
	, (vws.cGSTAmount)as cGSTAmount  
From       
 vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah, vwshops s      
Where       
 s.shopid = aIshopid And aiinvoiceid=siinvoiceid And aicancelled=0 And       
 aiproforma=0 And aIshopid = sIshopid And lah.aicAshinvoice =1      
      
UniOn All      
--hq serivce invoice dOne for shop      
Select       
 ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,       
 --COnvert(numeric(18,8),Sum(serviceqty * amount) ),      
 --COnvert(numeric(18,8),Sum(serviceqty * amount) *depexrate),      
 --COnvert(numeric(18,8),Sum(serviceqty * amount) *exchangerate),      
 COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  amount,             
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)damount,       
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)camount,       

 1 ,'hs', ai.departmentid  departmentid       
  ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount 
 ,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,
  convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount

From       
 accountsinvoiceheader ai, serviceinvoicedetails ser       
Where       
 ai.invoiceid = ser.invoiceid And ai.companyid =       
 ser.companyid And ai.cAshinvoice = 1 And ai.cancelled = 0 And ai.proforma = 0       
Group By     
 ai.companyid, ai.invoicedate,ai.invoiceid,ai.exchangerate,ai.bankcAshid,       
 ai.departmentid, depexrate, exchangerate      
      
UniOn All      
      
-- hari included From credit sales to correct the daily sales Summary report      
--Select       
-- ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,       
-- Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
-- (Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0)) -- +Isnull(Sum(invd.idcdcustcur),0)      
-- Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))  End Amount,       
-- Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
-- (Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0)) * ihdepexrate --  +Isnull(Sum(invd.idcdcustcur),0)      
-- Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))* ihdepexrate  End DAmount,       
-- Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
-- (Sum(Isnull(invd.idunitprice,0))+Isnull(ocd.ioAmount,0)) * ihExchangeRate -- +Isnull(Sum(invd.idcdcustcur),0)      
-- Else (Sum(Isnull(invd.idunitprice,0))+ Isnull(ocd.ioAmount,0))* ihExchangeRate End cAmount,       
-- 0 ihcAshinvoice, 'c' As transtype, ih.ihdepartmentid  departmentid       
--From       
-- losinvoiceheader ih       
-- Left Outer Join losinvoicedetail invd       
-- On ih.ihshopid = invd.idshopid And ih.ihinvoiceid = invd.idinvoiceid      
-- Left Outer Join       
-- (Select      
--  ioShopID,ioInvoiceID,Sum(ioAmount) ioAmount      
-- From      
--  losInvoiceOC       
-- Group By     
--  ioShopID,ioInvoiceID) ocd       
-- On ihshopid= ocd.ioShopid And ihinvoiceid=ocd.ioInvoiceID, Ashops s      
--Where       
-- ihcancelled=0 And ihcAshinvoice =0 And ih.ihproforma =0 And ih.ihtype='I'      
-- And ihshopid = s.shopid And ihcompanyid = s.COmpanyid      
--Group By    
-- ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,       
-- ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate, ocd.ioAmount,       
-- s.futurevarchar, ih.ihdutypaidby      
 --credit invoice(Excluding Other charges)
Select       
 ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,       
 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) 
 Else 
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))  
 End Amount,       
 
 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihdepexrate 
 Else
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))* ihdepexrate  
 End DAmount,     
 
 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0))) * ihExchangeRate
 Else
	(Sum(Isnull(invd.idunitprice,0)-isnull(idItemTaxAmount,0)))* ihExchangeRate 
 End cAmount, 
       
 0 ihcAshinvoice, 'c' As transtype, ih.ihdepartmentid  departmentid 
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihdepexrate)dGSTAmount
,convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount
 
From       
 losinvoiceheader ih       
 Left Outer Join losinvoicedetail invd       
 On ih.ihshopid = invd.idshopid And ih.ihinvoiceid = invd.idinvoiceid      
 ,Ashops s  
Where       
 ihcancelled=0 And ihcAshinvoice =0 And ih.ihproforma =0 And ih.ihtype='I'      
 And ihshopid = s.shopid And ihcompanyid = s.COmpanyid      

Group By   
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,       
 ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate,
 s.futurevarchar, ih.ihdutypaidby,ISNULL(ihuserid,0)           

union all

 --Credit Invoice (Other Charges only)
Select       
 ih.ihcompanyid, ih.ihshopid, ih.ihinvoicedate, ih.ihbankcAshaccid,       

 Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
	 convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))              
 Else 
	convert(numeric(18,8), sum(isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0)))              
 End Amount,       

Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) 
Else 
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihdepexrate) 
End DAmount,       

Case when s.futurevarchar ='B' And ih.ihdutypaidby='' Then       
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate) 
Else
   convert(numeric(18,8), sum((isnull(ocd.ioAmount,0)-isnull(ocd.ioServTaxAmount,0))) * ihexchangerate)
End cAmount,       

0 ihcAshinvoice, 'c' As transtype, ih.ihdepartmentid  departmentid 
,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0)))GSTAmount
,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihdepexrate)dGSTAmount
,convert(numeric(18,8),sum(isnull(ocd.ioServTaxAmount,0))* ihexchangerate)cGSTAmount

from losinvoiceheader  ih                  
	left outer join losInvoiceOC ocd  on ihshopid= ocd.ioShopid 
		and ihinvoiceid=ocd.ioInvoiceID         
	,ashops s, adepartmentmaster d                   
where   
   IHCANCELLED=0 and ihproforma=0 and ihshopid = shopid and                   
   ihcashinvoice=0 and ihdepartmentid = d.departmentid and ihtype ='i'            
group by  
 ihcompanyid, ihshopid, ihinvoicedate, ihinvoiceid, ihexchangerate,ihCustomerID,       
 ihbankcAshaccid,ihdepartmentid, ihdepexrate, ihexchangerate,
 s.futurevarchar, ih.ihdutypaidby,ISNULL(ihuserid,0)       
      
      
UniOn All      
      
--serviceinvoice      
Select       
 vws.sicompanyid, vws.sIshopid, vws.siinvoicedate, lah.aibankcAshid,       
 --COnvert(numeric(18,8),vws.siamount) As amount,       
 --COnvert(numeric(18,8),vws.siamount * aidepexrate) As damount,       
 --COnvert(numeric(18,8),vws.siamount * aiexchangerate) As camount,
 	convert(numeric(18,8),(vws.siamount))as  amount,   
	convert(numeric(18,8),(vws.sidamount))as damount,
	convert(numeric(18,8),(vws.sicamount))as camount, 
  lah.aicAshinvoice, 's' As transtype, lah.aidepartmentid  departmentid       
,(vws.GSTAmount)as GSTAmount
,(vws.dGSTAmount)as dGSTAmount
,(vws.cGSTAmount)as cGSTAmount

From       
 vwshopservicesalesWithOutGST vws , LOsAccountsInvoiceHeader lah      
Where       
 aiinvoiceid=siinvoiceid And aicancelled=0 And aiproforma=0 And aIshopid = sIshopid      
 And lah.aicAshinvoice=0      
      
-- hari included      
UniOn All      
--hq serivce invoice dOne for shop      
Select       
 ai.CompanyID, null, ai.invoicedate, ai.bankcAshid,       
 --COnvert(numeric(18,8),Sum(serviceqty * amount) ),       
 --COnvert(numeric(18,8),Sum(serviceqty * amount) * depexrate),      
 --COnvert(numeric(18,8),Sum(serviceqty * amount) * exchangerate),      
 COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0)))  amount,             
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* depexrate)damount,       
COnvert(numeric(18,8),Sum((serviceqty * amount)-isnull(TaxAmount,0))* exchangerate)camount,       

 0 ,'hs',ai.departmentid  departmentid       
 ,COnvert(numeric(18,8),sum(isnull(TaxAmount,0)))GSTAmount 
,convert(numeric(18,8),sum(isnull(TaxAmount,0))* depexrate)dGSTAmount,
convert(numeric(18,8),sum(isnull(TaxAmount,0))* exchangerate)cGSTAmount

From       
 accountsinvoiceheader ai, serviceinvoicedetails ser       
Where       
 ai.invoiceid = ser.invoiceid And ai.companyid =       
 ser.companyid And ai.cAshinvoice = 0 And ai.cancelled = 0 And ai.proforma = 0       
Group By    
 ai.companyid, ai.invoicedate, ai.invoiceid, ai.exchangerate,ai.bankcAshid,       
 ai.departmentid, depexrate, exchangerate      
      
-- hari included for service booking advances      
UniOn All      
      
Select       
 serbookhcompanyid, serbookhshopid, serbookadvancedate, serbookhcAshacc,       
 COnvert(numeric(18,8), serbookadvanceamount) ,      
 COnvert(numeric(18,8), serbookadvanceamount * serbookhdepexrate),      
 COnvert(numeric(18,8), serbookadvanceamount * serbookhcmpexrate), 1  ,'sb',       
 serbookhdepartmentid  
 ,0,0,0       
From LOsServiceBookingHeader      
       
Where       
 serbookhinpcancelled=0       
        And serbookadvanceamount>0      
      
-- hari included for service booking invoices which are cAsh invoices      
UniOn All      
      
Select       
 serinvhcompanyid, serinvhshopid, serinvhdate, serinvhcAshacc,       
 --COnvert(numeric(18,8), serinvhamount) ,       
 --COnvert(numeric(18,8), serinvhamount * seinvhdepexrate) ,       
 --COnvert(numeric(18,8), serinvhamount * serinvhcmpexrate) ,
 COnvert(numeric(18,8),serinvhamount-isnull(serinvhTaxamount,0)) ,       
 COnvert(numeric(18,8),(serinvhamount-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,       
 COnvert(numeric(18,8),(serinvhamount-isnull(serinvhTaxamount,0)) * serinvhcmpexrate),
  1 , 'sbi',       
 serinvhdepartmentid       
,convert(numeric(18,8),(isnull(serinvhTaxamount,0)))GSTAmount
,convert(numeric(18,8),(isnull(serinvhTaxamount,0))* seinvhdepexrate)dGSTAmount,
 convert(numeric(18,8),(isnull(serinvhTaxamount,0))* serinvhcmpexrate)cGSTAmount

From       
 losserviceinvheader       
Where       
 serinvhcancelled = 0   And       
 serinvhamount>0 And serinvhcAshacc Is Not Null      
      
-- hari included for service booking invoices which are credit invoices      
UniOn All      
      
Select       
 serinvhcompanyid, serinvhshopid, serinvhdate, serinvhcAshacc,       
 --COnvert(numeric(18,8), serinvhamount), COnvert(numeric(18,8),       
 --serinvhamount*seinvhdepexrate),      
 --COnvert(numeric(18,8), serinvhamount * serinvhcmpexrate)
  COnvert(numeric(18,8),serinvhamount-isnull(serinvhTaxamount,0)) ,       
 COnvert(numeric(18,8),(serinvhamount-isnull(serinvhTaxamount,0)) * seinvhdepexrate) ,       
 COnvert(numeric(18,8),(serinvhamount-isnull(serinvhTaxamount,0)) * serinvhcmpexrate),
 0 , 'sbi',       
 serinvhdepartmentid       
 ,convert(numeric(18,8),(isnull(serinvhTaxamount,0)))GSTAmount
,convert(numeric(18,8),(isnull(serinvhTaxamount,0))* seinvhdepexrate)dGSTAmount,
 convert(numeric(18,8),(isnull(serinvhTaxamount,0))* serinvhcmpexrate)cGSTAmount

From       
 losserviceinvheader       
Where       
 serinvhcancelled = 0 And       
 serinvhamount>0 And serinvhcAshacc Is null      
      
UniOn All      
      
Select  abh.abhcompanyid, abh.abhshopid,abhBillDate, abh.abhCAshAccId,       
COnvert(numeric(18,8), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,       
COnvert(numeric(18,8), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,       
COnvert(numeric(18,8), Isnull(abh.abhAmount,0)+Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,       
0, 'RBI' type , abh.abhdepartmentid departmentid 
   ,0,0,0     
From       
losApartmentBillHeader abh Where abh.abhCancelled = 0 And abh.abhCAshAccId Is null      
      
UniOn All      
      
Select  abh.abhcompanyid, abh.abhshopid,abhBillDate, abh.abhCAshAccId,       
COnvert(numeric(18,8), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) amount,       
COnvert(numeric(18,8), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhDepExRate dBillAmount,       
COnvert(numeric(18,8), Isnull(abh.abhAmount, 0) + Isnull(abh.abhOtherCharges,0)-Isnull(abh.abdDepositReturn,0)) * abhExRate cBillAmount,       
1, 'RBI' type , abh.abhdepartmentid departmentid 
,0,0,0       
From losApartmentBillHeader abh Where abh.abhCancelled = 0 And abh.abhCAshAccId Is Not Null      
      
UniOn All      
-- UTILITY BILL CREDIT INVOICES       
Select       
 tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhBillDate, tbh.tbhBankCAshID,       
 COnvert(numeric(18,8), Isnull(tbh.tbhAmount,0)) Amount,       
 COnvert(numeric(18,8), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,       
 COnvert(numeric(18,8), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,       
 0, 'UTB' type , tbh.tbhdepartmentid departmentid      
 ,0,0,0   
From       
 losTenantServiceBillHeader tbh, acustomermAster c      
Where       
 tbh.tbhCustomerID=c.customerID And tbh.tbhBankCAshID Is null And      
 tbh.tbhCancelled=0       
      
    UniOn All      
      
-- UTILITY BILL CAsH INVOICES      
    Select tbh.tbhCompanyid, tbhSHopID shopid, tbh.tbhBillDate, tbh.tbhBankCAshID,       
    COnvert(numeric(18,8), Isnull(tbh.tbhAmount,0)) Amount,       
    COnvert(numeric(18,8), Isnull(tbh.tbhAmount * tbh.tbhDepExRate,0)) dAmount,       
    COnvert(numeric(18,8), Isnull(tbh.tbhAmount * tbh.tbhExRate,0)) cAmount,       
    1, 'UTB' type , tbh.tbhdepartmentid departmentid    
    ,0,0,0     
    From losTenantServiceBillHeader tbh, acustomermAster c      
    Where  tbh.tbhCustomerID=c.customerID And tbh.tbhBankCAshID Is Not Null And      
    tbh.tbhCancelled=0       
      
    UniOn All      
      
    Select GrnCompanyID, grnhshopid, grnhGoodsReturnNoteDate, grnhCustomerId,       
    ---COnvert(numeric(18,8),Sum(grndunitprice))  amount,       
    ---COnvert(numeric(18,8),Sum(grndunitprice) * grnhdepExRate)  damount,      
    ---COnvert(numeric(18,8),Sum(grndunitprice) * grnhExchangeRate)  camount,  
   -convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0))))) amount,                 
   -convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhdepexRate) damount,                 
   -convert(numeric(18,8),(sum((GRNDunitprice-isnull(idItemTaxAmount,0)))) * grnhExchangeRate) camount, 
    0, 'GRD' As transtype, Grnhdepartmentid  departmentid       
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0)))GSTAmount
   ,-convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,
    -convert(numeric(18,8),sum(isnull(idItemTaxAmount,0))* grnhexchangerate)cGSTAmount

    From losGoodsReturnNoteHeader ih, losGoodsReturnNoteDetail invd     
    Where ih.GrnhShopid = invd.grndshopid And ih.GrnhGoodsreturnnoteID = invd.GrndreturnnoteID      
    And grnhCancel = 0  Group By grncompanyid, grnhshopid, grnhGoodsReturnNoteDate,       
    GrnhGoodsreturnnoteID, grnhCustomerID, grnhdepartmentid, grnhdepExRate, grnhExchangeRate      
              
    UniOn All    
    --Shop debit credit notes and handling debit notes which are debit to the  
    -- customer and hence act as invoices to be settled        
    Select  losdcnCompanyID, losdcnshopid,losdcndate, losdcncustomerid,    
    COnvert(numeric(18,8),Sum(losDCNAmount))  amount,       
    COnvert(numeric(18,8),Sum(losDCNAmount) * losdepexrate)  damount,      
    COnvert(numeric(18,8),Sum(losDCNAmount) * losexchangerate)  camount,        
    0, 'sdcn' As type , losdcndepartmentid
    ,0,0,0
     From Ashops s, acustomermAster c,     
    losdebitcreditnote Where  s.shopid = losdcnshopid And s.accountable Is Not Null     
    And c.customerid = losdcncustomerid And losdcncustomerid Is Not Null And       
    losdcncancelled =0 And losdcndebit =1  Group By losdcnCompanyID,losdcnshopid,    
    losdcndate, losdcncustomerid,losdepexrate, losexchangerate,losdcndepartmentid    
      
GO

------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Working of New Report -  Sales and Collection Detailed with GST Separately got from bijesh on 05.09.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionDetGSTSeparately')
   DROP view dbo.vwDailySalesCollectionDetGSTSeparately
GO
--Created by   : Bijesh.B
--Date         : 04/10/2012
--Comments     : GST Separated Reports
-----------------------------------------------------------------------------------------------   
--RefNo-1
--Modified by  : Bijesh.B
--Date         : 05/10/2012
--Comments     : No need to show dummy reciept in Depwise report
-----------------------------------------------------------------------------------------------   
 --Modified by     : Bijesh.B
--Modified Date  : 05/10/2012
--Desc           : Local purchase bill not calculating tax
-----------------------------------------------------------------------------------------------   

create VIEW [dbo].[vwDailySalesCollectionDetGSTSeparately] AS          
          
select companyid,departmentid, shopid, billdate,           
convert(numeric(18,8), sum(cashsales)) cashsales,           
convert(numeric(18,8), sum(dcashsales)) dcashsales,           
convert(numeric(18,8), sum(ccashsales)) ccashsales,           
convert(numeric(18,8), sum(receipts)) receipts,           
convert(numeric(18,8), sum(dreceipts)) dreceipts,           
convert(numeric(18,8), sum(creceipts)) creceipts,           
convert(numeric(18,8), sum(payments)) payments ,          
convert(numeric(18,8), sum(dpayments)) dpayments ,           
convert(numeric(18,8), sum(cpayments)) cpayments ,          
convert(numeric(18,8), sum(creditsales)) creditsales,           
convert(numeric(18,8), sum(dcreditsales)) dcreditsales,           
convert(numeric(18,8), sum(ccreditsales)) ccreditsales,           
convert(numeric(18,8), sum(creditcard)) as creditcard,           
convert(numeric(18,8), sum(dcreditcard)) as dcreditcard,           
convert(numeric(18,8), sum(ccreditcard)) as ccreditcard,           
convert(numeric(18,8), sum(debitcard)) as debitcard,          
convert(numeric(18,8), sum(ddebitcard)) as ddebitcard,           
convert(numeric(18,8), sum(cdebitcard)) as cdebitcard,          
convert(numeric(18,8), sum(localpurchase)) as localpurchase,           
convert(numeric(18,8), sum(dlocalpurchase)) as dlocalpurchase,          
convert(numeric(18,8), sum(clocalpurchase)) as clocalpurchase,  
convert(numeric(18,8), sum(Exchange)) as Exchange,           
convert(numeric(18,8), sum(dExchange)) as dExchange,  
convert(numeric(18,8), sum(cExchange)) as cExchange,  
convert(numeric(18,8), sum(GoodsReturn)) as GoodsReturn,           
convert(numeric(18,8), sum(dGoodsReturn)) as dGoodsReturn,  
convert(numeric(18,8), sum(cGoodsReturn)) as cGoodsReturn        
--RefNo-2 start -------------------
,convert(numeric(18,8), sum(PdChequeSales)) PdChequeSales,                           
convert(numeric(18,8), sum(dPdChequeSales)) dPdChequeSales,                           
convert(numeric(18,8), sum(cPdChequeSales)) cPdChequeSales
--RefNo-2 end -------------------                         
,convert(numeric(18,8),sum(GSTAmount))GSTAmount,
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount
from          
(select cs.companyid ,departmentid, shopid, billdate,         
case when cash=1 and am.misc='CA' then sum(Amount) else 0 end cashsales,           
case when cash=1 and am.misc='CA' then sum(damount) else 0 end  dcashsales,         
case when cash=1 and am.misc='CA' then sum(camount) else 0 end  ccashsales,        
case when cash=1 and am.misc='CC' then sum(Amount) else 0 end creditcard,           
case when cash=1 and am.misc='CC' then sum(damount) else 0 end  dcreditcard,         
case when cash=1 and am.misc='CC' then sum(camount) else 0 end  ccreditcard,        
case when cash=1 and am.misc='DC' then sum(Amount) else 0 end debitcard,           
case when cash=1 and am.misc='DC' then sum(damount) else 0 end  ddebitcard,         
case when cash=1 and am.misc='DC' then sum(camount) else 0 end  cdebitcard,        
0.0 as receipts, 0.0 as dreceipts, 0.0 as creceipts,         
0.0 as payments, 0.0 as dpayments, 0.0 as cpayments,           
--RefNo-2 start commented below -----------------------------                      
/*
case when cash=0 then sum(Amount) else 0 end creditsales,           
case when cash=0 then sum(damount) else 0 end  dcreditsales,         
case when cash=0 then sum(camount) else 0 end  ccreditsales,        
*/
case when cash=0 and (cs.transtype<>'PD CHEQUE') then sum(Amount) else 0 end creditsales,                           
case when cash=0 and (cs.transtype<>'PD CHEQUE') then sum(damount) else 0 end  dcreditsales,                         
case when cash=0 and (cs.transtype<>'PD CHEQUE') then sum(camount) else 0 end  ccreditsales,                        
--RefNo-2 ends ----------------------------------------------
0.0 as localpurchase, 0.0 as dlocalpurchase , 0.0 as clocalpurchase,  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn         
--RefNo-2 start ---------------------------------------------                      
,case when cash=0 and (cs.transtype='PD CHEQUE') then sum(Amount) else 0 end PdChequeSales,                     
case when cash=0 and (cs.transtype='PD CHEQUE') then sum(damount) else 0 end dPdChequeSales,                   
case when cash=0 and (cs.transtype='PD CHEQUE') then sum(camount) else 0 end cPdChequeSales                  
--RefNo-2 ends ---------------------------------------------                      
,sum(GSTAmount)GSTAmount,sum(dGSTAmount)dGSTAmount,sum(cGSTAmount)cGSTAmount
from vwCAshSalesDetGSTSeprately cs left outer join aaccountmaster am   on        
cs.accountid = am.accountid and cs.companyid = am.companyid   
where transtype not in ('GRD','E')       
group by cs.companyid ,departmentid, shopid, billdate, am.misc, cash -- cashsales           
,cs.transtype --RefNo2                

--RefNo-1 start commented below        
--union all          
          
--select drcompanyid, drdepartmentid, drshopid, drdate, 0.0 as cashsales, 0.0 as dcashsales,           
--0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,           
--0.0 as ddebitcard, 0.0 as cdebitcard,           
--convert(numeric(18,8),sum(drAmount)) receipts,           
--convert(numeric(18,8),sum(drAmount* drdepexrate)) dreceipts,           
--convert(numeric(18,8),sum(drAmount*drexchangerate)) creceipts,           
--0.0 as payments, 0.0 as dpayments,           
--0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales,           
--0.0 as ccreditsales, 0.0 as localpurchase,          
--0.0 as dlocalpurchase, 0.0 as clocalpurchase,  
--0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
--0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                 
----RefNo-2 start -------------------
--,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
--0.0 as cPdChequeSales
--,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
----RefNo-2 ends -------------------                          
--from losDummyReceiptHeader rh, acustomermaster cm           
--where drcancelled = 0           
--and rh.drcustomerid = cm.customerid           
--and rh.drcompanyid = cm.companyid           
--group by drcompanyid, drdepartmentid, drshopid, drdate          

--RefNo-1 ends
          
union all           
          
--selects the receipts done in the HQ for the shop other than the shop receipts by checking the           
--exchange nature field. iF THE exchangenature field is null then the receipt is done only in           
--hq and if the exchangenature field is not null then the shop receipts will only taken          
--for receipts          
select rh.companyid, rh.departmentid, 0, rh.receiptdate, 0.0 as cashsales,           
0.0 as dcashsales,           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,           
0.0 as ddebitcard, 0.0 as cdebitcard,           
convert(numeric(18,8),sum(rd.AmountReceived)) receipts,           
convert(numeric(18,8),sum(rd.AmountReceived )) dreceipts,           
convert(numeric(18,8),sum(rd.AmountReceived )) creceipts, 0.0 as payments,           
0.0 as dpayments,           
0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales, 0.0 as ccreditsales,           
0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase ,  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                   
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
--RefNo-2 ends -------------------                          
from receiptvoucherheader rh, receiptvoucherdetails rd           
where rh.receiptid = rd.receiptid           
and rh.companyid = rd.companyid          
and rh.cancelled=0          
and ((rh.dummyreceiptid is null and rh.recshopid is null)           
      or (rh.dummyreceiptid=0 and rh.recshopid=0))          
group by rh.companyid,rh.departmentid, rh.receiptdate          
    
union all       
--For Populating Other Receipts     
-- Other Receipts is done in Departments So ShopId will be 0    
select rh.companyid, rh.departmentid, 0, rh.receiptdate, 0.0 as cashsales,           
0.0 as dcashsales,           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,           
0.0 as ddebitcard, 0.0 as cdebitcard,           
convert(numeric(18,8),sum(Amount)) receipts,           
convert(numeric(18,8),sum(Amount * depexrate)) dreceipts,           
convert(numeric(18,8),sum(Amount* exchangerate)) creceipts, 0.0 as payments,           
0.0 as dpayments,           
0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales, 0.0 as ccreditsales,           
0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase ,  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                   
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
--RefNo-2 ends -------------------                          
from receiptvoucherheader rh          
where  rh.cancelled=0     
and rh.ReceiptID not in (select ReceiptID from ReceiptVoucherDetails)       
and ((rh.dummyreceiptid is null and rh.recshopid is null)           
      or (rh.dummyreceiptid=0 and rh.recshopid=0))          
group by rh.companyid,rh.departmentid, rh.receiptdate       
     
union all          
          
select phcompanyid,phdepartmentid, phshopid, phPaymentDate, 0.0 as cashsales, 0.0 as dcashsales,           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,           
0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts, 0.0 as creceipts,           
convert(numeric(18,8),sum(phAmount)) as payments,           
convert(numeric(18,8),sum(phAmount* phdepexrate)) as dpayments,           
convert(numeric(18,8),sum(phAmount* phexchangerate)) as cpayments,           
0.0 as creditsales , 0.0 as dcreditsales, 0.0 as ccreditsales, 0.0 as localpurchase,           
0.0 as dlocalpurchase, 0.0 as clocalpurchase ,  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                   
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
--RefNo-2 ends -------------------                          
from LOsPaymentVoucherHeader ph           
where phcancelled = 0            
group by phcompanyid, phdepartmentid, phshopid, phPaymentDate          
          
union all          
--local purchase - madhu 23/08/01          

--select lh.lphcompanyid,lh.lphdepartmentid,lh.lphshopid,lh.lphbilldate, 0.0 cashsales,           
--0.0 dcashsales, 0.0 ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard,          
--0.0 as debitcard, 0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts,          
--0.0 as creceipts, 0.0 as payments, 0.0 as dpayments, 0.0 as cpayments, 0.0 as creditsales,           
--0.0 as dcreditsales, 0.0 as ccreditsales, convert(numeric(18,8),sum(lphbillamount)) as localpurchase,          
--convert(numeric(18,8),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,           
--convert(numeric(18,8),sum(lphbillamount*lphexchangerate)) as clocalpurchase ,  
--0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
--0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                
----RefNo-2 start -------------------
--,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
--0.0 as cPdChequeSales
--,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
----RefNo-2 ends -------------------                          
--from loslocalpurchaseheader lh,adepartmentmaster d where          
--lh.lphDepartmentID=d.departmentid  and lh.lphcashpurchase=1  and lphcancelled=0          
--group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate  
select lh.lphcompanyid,lh.lphdepartmentid,lh.lphshopid,lh.lphbilldate, 0.0 cashsales,           
0.0 dcashsales, 0.0 ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard,          
0.0 as debitcard, 0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts,          
0.0 as creceipts, 0.0 as payments, 0.0 as dpayments, 0.0 as cpayments, 0.0 as creditsales,           
0.0 as dcreditsales, 0.0 as ccreditsales, 
convert(numeric(18,8),sum(lpdItemUnitPrice)) as localpurchase,          
convert(numeric(18,8),sum(isnull(lpdItemUnitPrice,0))* lphdepexrate)dlocalpurchase,
convert(numeric(18,8),sum(isnull(lpdItemUnitPrice,0))* lphexchangerate)clocalpurchase,
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
,convert(numeric(18,8),sum(isnull(lpdItemTaxAmount,0)))GSTAmount,
convert(numeric(18,8),sum(isnull(lpdItemTaxAmount,0))* lphdepexrate)dGSTAmount,
convert(numeric(18,8),sum(isnull(lpdItemTaxAmount,0))* lphexchangerate)cGSTAmount
--RefNo-2 ends -------------------                          
from loslocalpurchaseheader lh,loslocalpurchaseDetail ld, adepartmentmaster d where  
lh.lphBillID=ld.lpdBillID and lh.lphShopID=ld.lpdShopID and       
lh.lphDepartmentID=d.departmentid  and lh.lphcashpurchase=1  and lphcancelled=0          
group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate ,lphdepexrate,lphexchangerate 

--Exchange And Goods Return  
union all   
select cs.companyid ,departmentid, shopid, billdate,         
0.00 as cashsales, 0.00 as  dcashsales,0.00 as  ccashsales,        
0.00 as  creditcard,0.00 as  dcreditcard,0.00 as  ccreditcard,        
0.00 as  debitcard,0.00 as  ddebitcard,0.00 as  cdebitcard,        
0.0 as receipts, 0.0 as dreceipts, 0.0 as creceipts,         
0.0 as payments, 0.0 as dpayments, 0.0 as cpayments,           
0.0 as creditsales,0.0 as dcreditsales,0.0 as ccreditsales,        
0.0 as localpurchase, 0.0 as dlocalpurchase , 0.0 as clocalpurchase,  
case when cash=1 then sum(Amount) else 0 end Exchange,  
case when cash=1 then sum(Amount) else 0 end dExchange,  
case when cash=1 then sum(Amount) else 0 end cExchange,  
--RefNo-2 start -------------------
/*
case when cash=0 then sum(Amount) else 0 end  GoodsReturn,  
case when cash=0 then sum(dAmount) else 0 end dGoodsReturn,  
case when cash=0 then sum(cAmount) else 0 end cGoodsReturn         
*/
case when cash=0 and (cs.transtype<>'PD CHEQUE') then sum(Amount) else 0 end  GoodsReturn,  
case when cash=0 and (cs.transtype<>'PD CHEQUE') then sum(dAmount) else 0 end dGoodsReturn,  
case when cash=0 and (cs.transtype<>'PD CHEQUE') then sum(cAmount) else 0 end cGoodsReturn         
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
--RefNo-2 ends -------------------                          
from vwCAshSalesDetGSTSeprately cs left outer join aaccountmaster am   on        
cs.accountid = am.accountid and cs.companyid = am.companyid   
where transtype  in ('GRD','E')       
group by cs.companyid ,departmentid, shopid, billdate, am.misc, cash
,cs.transtype --RefNo-2
) summary   
group by companyid ,departmentid, shopid, billdate          
                          
go

------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Working of New Report -  Sales and Collection Detailed with GST Separately got from bijesh on 05.09.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwDailySalesCollectionDetShopWiseGSTSeparately')
   DROP view dbo.vwDailySalesCollectionDetShopWiseGSTSeparately
GO
--Created by   : Bijesh.B
--Date         : 04/10/2012
--Comments     : GST Separated Reports
-----------------------------------------------------------------------------------------------   
--RefNo-1
--Modified by     : Bijesh.B
--Modified Date  : 05/10/2012
--Desc           :In shopwise report, they don't need receipts done in Accounts
-----------------------------------------------------------------------------------------------   
--Modified by     : Bijesh.B
--Modified Date  : 05/10/2012
--Desc           : Local purchase bill not calculating tax
-----------------------------------------------------------------------------------------------   

create VIEW [dbo].[vwDailySalesCollectionDetShopWiseGSTSeparately] AS          
          
select companyid,departmentid, shopid, billdate,           
convert(numeric(18,8), sum(cashsales)) cashsales,           
convert(numeric(18,8), sum(dcashsales)) dcashsales,           
convert(numeric(18,8), sum(ccashsales)) ccashsales,           
convert(numeric(18,8), sum(receipts)) receipts,           
convert(numeric(18,8), sum(dreceipts)) dreceipts,           
convert(numeric(18,8), sum(creceipts)) creceipts,           
convert(numeric(18,8), sum(payments)) payments ,          
convert(numeric(18,8), sum(dpayments)) dpayments ,           
convert(numeric(18,8), sum(cpayments)) cpayments ,          
convert(numeric(18,8), sum(creditsales)) creditsales,           
convert(numeric(18,8), sum(dcreditsales)) dcreditsales,           
convert(numeric(18,8), sum(ccreditsales)) ccreditsales,           
convert(numeric(18,8), sum(creditcard)) as creditcard,           
convert(numeric(18,8), sum(dcreditcard)) as dcreditcard,           
convert(numeric(18,8), sum(ccreditcard)) as ccreditcard,           
convert(numeric(18,8), sum(debitcard)) as debitcard,          
convert(numeric(18,8), sum(ddebitcard)) as ddebitcard,           
convert(numeric(18,8), sum(cdebitcard)) as cdebitcard,          
convert(numeric(18,8), sum(localpurchase)) as localpurchase,           
convert(numeric(18,8), sum(dlocalpurchase)) as dlocalpurchase,          
convert(numeric(18,8), sum(clocalpurchase)) as clocalpurchase,  
convert(numeric(18,8), sum(Exchange)) as Exchange,           
convert(numeric(18,8), sum(dExchange)) as dExchange,  
convert(numeric(18,8), sum(cExchange)) as cExchange,  
convert(numeric(18,8), sum(GoodsReturn)) as GoodsReturn,           
convert(numeric(18,8), sum(dGoodsReturn)) as dGoodsReturn,  
convert(numeric(18,8), sum(cGoodsReturn)) as cGoodsReturn        
--RefNo-2 start -------------------
,convert(numeric(18,8), sum(PdChequeSales)) PdChequeSales,                           
convert(numeric(18,8), sum(dPdChequeSales)) dPdChequeSales,                           
convert(numeric(18,8), sum(cPdChequeSales)) cPdChequeSales
--RefNo-2 end -------------------                         
,convert(numeric(18,8),sum(GSTAmount))GSTAmount,
convert(numeric(18,8),sum(dGSTAmount))dGSTAmount,
convert(numeric(18,8),sum(cGSTAmount))cGSTAmount
from          
(select cs.companyid ,departmentid, shopid, billdate,         
case when cash=1 and am.misc='CA' then sum(Amount) else 0 end cashsales,           
case when cash=1 and am.misc='CA' then sum(damount) else 0 end  dcashsales,         
case when cash=1 and am.misc='CA' then sum(camount) else 0 end  ccashsales,        
case when cash=1 and am.misc='CC' then sum(Amount) else 0 end creditcard,           
case when cash=1 and am.misc='CC' then sum(damount) else 0 end  dcreditcard,         
case when cash=1 and am.misc='CC' then sum(camount) else 0 end  ccreditcard,        
case when cash=1 and am.misc='DC' then sum(Amount) else 0 end debitcard,           
case when cash=1 and am.misc='DC' then sum(damount) else 0 end  ddebitcard,         
case when cash=1 and am.misc='DC' then sum(camount) else 0 end  cdebitcard,        
0.0 as receipts, 0.0 as dreceipts, 0.0 as creceipts,         
0.0 as payments, 0.0 as dpayments, 0.0 as cpayments,           
--RefNo-2 start commented below -----------------------------                      
/*
case when cash=0 then sum(Amount) else 0 end creditsales,           
case when cash=0 then sum(damount) else 0 end  dcreditsales,         
case when cash=0 then sum(camount) else 0 end  ccreditsales,        
*/
case when cash=0 and (cs.transtype<>'PD CHEQUE') then sum(Amount) else 0 end creditsales,                           
case when cash=0 and (cs.transtype<>'PD CHEQUE') then sum(damount) else 0 end  dcreditsales,                         
case when cash=0 and (cs.transtype<>'PD CHEQUE') then sum(camount) else 0 end  ccreditsales,                        
--RefNo-2 ends ----------------------------------------------
0.0 as localpurchase, 0.0 as dlocalpurchase , 0.0 as clocalpurchase,  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn         
--RefNo-2 start ---------------------------------------------                      
,case when cash=0 and (cs.transtype='PD CHEQUE') then sum(Amount) else 0 end PdChequeSales,                     
case when cash=0 and (cs.transtype='PD CHEQUE') then sum(damount) else 0 end dPdChequeSales,                   
case when cash=0 and (cs.transtype='PD CHEQUE') then sum(camount) else 0 end cPdChequeSales                  
--RefNo-2 ends ---------------------------------------------                      
,sum(GSTAmount)GSTAmount,sum(dGSTAmount)dGSTAmount,sum(cGSTAmount)cGSTAmount
from vwCAshSalesDetGSTSeprately cs left outer join aaccountmaster am   on        
cs.accountid = am.accountid and cs.companyid = am.companyid   
where transtype not in ('GRD','E')       
group by cs.companyid ,departmentid, shopid, billdate, am.misc, cash -- cashsales           
,cs.transtype --RefNo2                
        
union all          
          
select drcompanyid, drdepartmentid, drshopid, drdate, 0.0 as cashsales, 0.0 as dcashsales,           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,           
0.0 as ddebitcard, 0.0 as cdebitcard,           
convert(numeric(18,8),sum(drAmount)) receipts,           
convert(numeric(18,8),sum(drAmount* drdepexrate)) dreceipts,           
convert(numeric(18,8),sum(drAmount*drexchangerate)) creceipts,           
0.0 as payments, 0.0 as dpayments,           
0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales,           
0.0 as ccreditsales, 0.0 as localpurchase,          
0.0 as dlocalpurchase, 0.0 as clocalpurchase,  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                 
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
--RefNo-2 ends -------------------                          
from losDummyReceiptHeader rh, acustomermaster cm           
where drcancelled = 0           
and rh.drcustomerid = cm.customerid           
and rh.drcompanyid = cm.companyid           
group by drcompanyid, drdepartmentid, drshopid, drdate          

--RefN0-1 start commented below          
--union all           
          
----selects the receipts done in the HQ for the shop other than the shop receipts by checking the           
----exchange nature field. iF THE exchangenature field is null then the receipt is done only in           
----hq and if the exchangenature field is not null then the shop receipts will only taken          
----for receipts          
--select rh.companyid, rh.departmentid, 0, rh.receiptdate, 0.0 as cashsales,           
--0.0 as dcashsales,           
--0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,           
--0.0 as ddebitcard, 0.0 as cdebitcard,           
--convert(numeric(18,8),sum(rd.AmountReceived)) receipts,           
--convert(numeric(18,8),sum(rd.AmountReceived )) dreceipts,           
--convert(numeric(18,8),sum(rd.AmountReceived )) creceipts, 0.0 as payments,           
--0.0 as dpayments,           
--0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales, 0.0 as ccreditsales,           
--0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase ,  
--0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
--0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                   
----RefNo-2 start -------------------
--,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
--0.0 as cPdChequeSales
--,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
----RefNo-2 ends -------------------                          
--from receiptvoucherheader rh, receiptvoucherdetails rd           
--where rh.receiptid = rd.receiptid           
--and rh.companyid = rd.companyid          
--and rh.cancelled=0          
--and ((rh.dummyreceiptid is null and rh.recshopid is null)           
--      or (rh.dummyreceiptid=0 and rh.recshopid=0))          
--group by rh.companyid,rh.departmentid, rh.receiptdate          
    
--union all       
----For Populating Other Receipts     
---- Other Receipts is done in Departments So ShopId will be 0    
--select rh.companyid, rh.departmentid, 0, rh.receiptdate, 0.0 as cashsales,           
--0.0 as dcashsales,           
--0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,           
--0.0 as ddebitcard, 0.0 as cdebitcard,           
--convert(numeric(18,8),sum(Amount)) receipts,           
--convert(numeric(18,8),sum(Amount * depexrate)) dreceipts,           
--convert(numeric(18,8),sum(Amount* exchangerate)) creceipts, 0.0 as payments,           
--0.0 as dpayments,           
--0.0 as cpayments, 0.0 as creditsales, 0.0 as dcreditsales, 0.0 as ccreditsales,           
--0.0 as localpurchase, 0.0 as dlocalpurchase, 0.0 as clocalpurchase ,  
--0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
--0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                   
----RefNo-2 start -------------------
--,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
--0.0 as cPdChequeSales
--,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
----RefNo-2 ends -------------------                          
--from receiptvoucherheader rh          
--where  rh.cancelled=0     
--and rh.ReceiptID not in (select ReceiptID from ReceiptVoucherDetails)       
--and ((rh.dummyreceiptid is null and rh.recshopid is null)           
--      or (rh.dummyreceiptid=0 and rh.recshopid=0))          
--group by rh.companyid,rh.departmentid, rh.receiptdate       

--RefN0-1 ends
     
union all          
          
select phcompanyid,phdepartmentid, phshopid, phPaymentDate, 0.0 as cashsales, 0.0 as dcashsales,           
0.0 as ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard, 0.0 as debitcard,           
0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts, 0.0 as creceipts,           
convert(numeric(18,8),sum(phAmount)) as payments,           
convert(numeric(18,8),sum(phAmount* phdepexrate)) as dpayments,           
convert(numeric(18,8),sum(phAmount* phexchangerate)) as cpayments,           
0.0 as creditsales , 0.0 as dcreditsales, 0.0 as ccreditsales, 0.0 as localpurchase,           
0.0 as dlocalpurchase, 0.0 as clocalpurchase ,  
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                   
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
--RefNo-2 ends -------------------                          
from LOsPaymentVoucherHeader ph           
where phcancelled = 0            
group by phcompanyid, phdepartmentid, phshopid, phPaymentDate          
          
union all          
--local purchase - madhu 23/08/01          
--select lh.lphcompanyid,lh.lphdepartmentid,lh.lphshopid,lh.lphbilldate, 0.0 cashsales,           
--0.0 dcashsales, 0.0 ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard,          
--0.0 as debitcard, 0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts,          
--0.0 as creceipts, 0.0 as payments, 0.0 as dpayments, 0.0 as cpayments, 0.0 as creditsales,           
--0.0 as dcreditsales, 0.0 as ccreditsales, convert(numeric(18,8),sum(lphbillamount)) as localpurchase,          
--convert(numeric(18,8),sum(lphbillamount* lphdepexrate)) as dlocalpurchase,           
--convert(numeric(18,8),sum(lphbillamount*lphexchangerate)) as clocalpurchase ,  
--0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
--0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                
----RefNo-2 start -------------------
--,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
--0.0 as cPdChequeSales
--,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
----RefNo-2 ends -------------------                          
--from loslocalpurchaseheader lh,adepartmentmaster d where          
--lh.lphDepartmentID=d.departmentid  and lh.lphcashpurchase=1  and lphcancelled=0          
--group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate  

select lh.lphcompanyid,lh.lphdepartmentid,lh.lphshopid,lh.lphbilldate, 0.0 cashsales,           
0.0 dcashsales, 0.0 ccashsales, 0.0 as creditcard, 0.0 as dcreditcard, 0.0 as ccreditcard,          
0.0 as debitcard, 0.0 as ddebitcard, 0.0 as cdebitcard, 0.0 as receipts, 0.0 as dreceipts,          
0.0 as creceipts, 0.0 as payments, 0.0 as dpayments, 0.0 as cpayments, 0.0 as creditsales,           
0.0 as dcreditsales, 0.0 as ccreditsales, 
convert(numeric(18,8),sum(lpdItemUnitPrice)) as localpurchase,          
convert(numeric(18,8),sum(isnull(lpdItemUnitPrice,0))* lphdepexrate)dlocalpurchase,
convert(numeric(18,8),sum(isnull(lpdItemUnitPrice,0))* lphexchangerate)clocalpurchase,
0.0 as Exchange, 0.0 as dExchange,0.0 as cExchange,  
0.0 as GoodsReturn, 0.0 as dGoodsReturn,0.0 as cGoodsReturn                
--RefNo-2 start -------------------
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
,convert(numeric(18,8),sum(isnull(lpdItemTaxAmount,0)))GSTAmount,
convert(numeric(18,8),sum(isnull(lpdItemTaxAmount,0))* lphdepexrate)dGSTAmount,
convert(numeric(18,8),sum(isnull(lpdItemTaxAmount,0))* lphexchangerate)cGSTAmount
--RefNo-2 ends -------------------                          
from loslocalpurchaseheader lh,loslocalpurchaseDetail ld, adepartmentmaster d where  
lh.lphBillID=ld.lpdBillID and lh.lphShopID=ld.lpdShopID and       
lh.lphDepartmentID=d.departmentid  and lh.lphcashpurchase=1  and lphcancelled=0          
group by lh.lphcompanyid,lphdepartmentid,lphshopid,lphbilldate ,lphdepexrate,lphexchangerate 
	

--Exchange And Goods Return  
union all   
select cs.companyid ,departmentid, shopid, billdate,         
0.00 as cashsales, 0.00 as  dcashsales,0.00 as  ccashsales,        
0.00 as  creditcard,0.00 as  dcreditcard,0.00 as  ccreditcard,        
0.00 as  debitcard,0.00 as  ddebitcard,0.00 as  cdebitcard,        
0.0 as receipts, 0.0 as dreceipts, 0.0 as creceipts,         
0.0 as payments, 0.0 as dpayments, 0.0 as cpayments,           
0.0 as creditsales,0.0 as dcreditsales,0.0 as ccreditsales,        
0.0 as localpurchase, 0.0 as dlocalpurchase , 0.0 as clocalpurchase,  
case when cash=1 then sum(Amount) else 0 end Exchange,  
case when cash=1 then sum(Amount) else 0 end dExchange,  
case when cash=1 then sum(Amount) else 0 end cExchange,  
--RefNo-2 start -------------------
/*
case when cash=0 then sum(Amount) else 0 end  GoodsReturn,  
case when cash=0 then sum(dAmount) else 0 end dGoodsReturn,  
case when cash=0 then sum(cAmount) else 0 end cGoodsReturn         
*/
case when cash=0 and (cs.transtype<>'PD CHEQUE') then sum(Amount) else 0 end  GoodsReturn,  
case when cash=0 and (cs.transtype<>'PD CHEQUE') then sum(dAmount) else 0 end dGoodsReturn,  
case when cash=0 and (cs.transtype<>'PD CHEQUE') then sum(cAmount) else 0 end cGoodsReturn         
,0.0 as PdChequeSales, 0.0 as dPdChequeSales,                           
0.0 as cPdChequeSales
,0.0 GSTAmount,0.0 dGSTAmount,0.0 cGSTAmount    
--RefNo-2 ends -------------------                          
from vwCAshSalesDetGSTSeprately cs left outer join aaccountmaster am   on        
cs.accountid = am.accountid and cs.companyid = am.companyid   
where transtype  in ('GRD','E')       
group by cs.companyid ,departmentid, shopid, billdate, am.misc, cash
,cs.transtype --RefNo-2
) summary   
group by companyid ,departmentid, shopid, billdate          
                          
go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:SheeshA Update send to rahul on 9.10.2012 from Benzi
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
 
IF EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'vwservicecatagoryschedule'))
BEGIN
	DROP VIEW vwservicecatagoryschedule
END 

GO
 -- Created By :- Benzigar S D
 -- Created On :- 04/10/2012
 -- Purpose    :- For service catagorywise scheduling
 --------------------------------------------------------------
  Create view vwservicecatagoryschedule 
  AS
  select a.serinvhid,serinvhshopid,serinvdserviceid,sername,serDefaultDurMin,sercategid,sercatname from  
 (select serinvhid,serinvhshopid,serinvdserviceid,sername,serDefaultDurMin,ascy.sercategid,sercatname from  
 losserviceheader ls Left outer join  losinvservicedetails ld on  
 ld.serinvdshopid=ls.serinvhshopid and ld.serinvdinvoiceid=ls.serinvhid  
 and ls.serinvhjobinvcancelled=0 inner join aservicemaster asm on  
 asm.serid=serinvdserviceid inner join aservicecategory ascy on ascy.sercategid=asm.sercategid)a 
 
 Go


go
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:SheeshA Update send to rahul on 9.10.2012 from Benzi
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
IF EXISTS (SELECT * FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'VWServiceScheduleCatagoryGroup'))
BEGIN
	DROP VIEW VWServiceScheduleCatagoryGroup
END 

GO
-- Created By :- Benzigar S D
 -- Created On :- 04/10/2012
 -- Purpose    :- For service catagorywise scheduling
 --------------------------------------------------------------
CREATE View VWServiceScheduleCatagoryGroup
AS
 SELECT OutTab.serinvhid,OutTab.serinvhshopid,OutTab.sercategid,
      sername = 
              STUFF ( ( SELECT ','+InrTab.sername
						FROM [vwservicecatagoryschedule] InrTab
						WHERE InrTab.serinvhid = OutTab.serinvhid
						 AND  InrTab.serinvhshopid = OutTab.serinvhshopid
						 and  InrTab.sercategid = OutTab.sercategid
						 and  InrTab.sercatname = OutTab.sercatname
						ORDER BY InrTab.sername
						FOR XML PATH(''),TYPE 
					   ).value('.','VARCHAR(MAX)') 
					  , 1,1,SPACE(0)),SUM(serDefaultDurMin) serDefaultDurMin,OutTab.sercatname
FROM [vwservicecatagoryschedule] OutTab 
GROUP BY OutTab.serinvhid,OutTab.[serinvhshopid],OutTab.[sercategid],OutTab.[sercatname] ;

Go


go

------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Problem in Stock verification got from jyothish 09.10.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spUlShopSv]') AND type in (N'P', N'PC'))
  Drop Procedure spUlShopSv
go



/****** Object:  Stored Procedure dbo.spULshopSV    Script Date: 18/01/2003 9:45:46 PM ******/    
-- Modified      : 17/07/2002    
-- Modified by   : leo    
-----------------------------------------    
-- Modified on      : 03/01/2003    
-- Modified by      : Kishore    
-- Comments         : Added code to insert depAmount and to convert amount    
-----------------------------------------    
-- Modified on      : 09/10/2012    
-- Modified by      : jyothish    
-- Comments         : avoide rate cheking

create  proc [dbo].[spUlShopSv] @intCompanyId as int, @intShop as int as     
begin    
 Declare @intJournalId as int,@intJournalDetailId as int,@intsvId as int,@intFinancialId as int,    
 @strsvNo as varchar(50),@dtsvDate as datetime,@strRemarks as varchar(500),@intDepartmentId as int,    
 @numSvAddAmt as numeric(18,2),  @numSvDeductAmt as numeric(18,2),@intCompanyCurId as int,    
 @intInventoryAccId as int,  @intswoAccId as int,  @intsrecAccId as int,@dtutime as datetime,    
 @intFailcount as int,  @strzerorate as varchar(1),  @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),    
 @numTemp Numeric (18, 2)    
  
 --get the companyCurrencyId     
 SELECT @intCompanyCurId = CurrencyId FROM acompanymaster WHERE CompanyId = @intCompanyId    
    
 select @intswoAccId = stockWriteoffAccId from aShops where ShopId = @intShop    
    
 -- in future int the stock recovery accountId is stored    
 select @intInventoryAccId = InventoryId, @intsrecAccId = futureint,     
  @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 svcur cursor for     
 SELECT svhId, svhno, svhdate, svhremarks, updatetime, svhdepartmentId,    
  svhConExRate, svhDepExRate, svhExchangeRates    
 FROM losstockverificationheader     
 WHERE svhcancelled =0 and svhShopId = 2   and svhposted =0     
  
 open svcur    
    
 fetch next from  svcur into @intsvId, @strsvno, @dtsvDate, @strRemarks, @dtutime,    
  @intDepartmentId, @numConExRate, @numDepExRate, @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 @dtsvDate     
  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 losstockverificationdetail, aitem where     
 -- svdId = @intsvId and svdShopId = @intShop and svditemId = itemId     
 -- and ( svdCostPrice =null or svdCostPrice=0) and (itemrate=0 or itemrate is null)  
  
 --  ----- to check item rate =0 or null  is exist in vwshopbincard
     
 -- if  @intFailcount <> 0
 -- begin
  
 --  --select  @intFailcount= COUNT (*)  from vwShopBincardAudit where  ShopId=@intShop  and ItemId in ( 
	--  -- select svditemId from losstockverificationdetail, aitem where     
	--  --svdId = @intsvId and svdShopId = @intShop and svditemId = itemId     
	--  --and ( svdCostPrice =null or svdCostPrice=0) and (itemrate=0 or itemrate is null)  )
	--set  @intFailcount=0   
 -- end
     
 
  -- 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 losstockverificationdetail set svdCostPrice = itemrate from     
   aitem where ( svdCostPrice = null or svdCostPrice =0) and svdId =     
   @intsvId and svdShopId = @intShop and svditemId = itemId     
  
   --getting the total amount with qty and item cost price    
   select @numSvDeductAmt = isnull(sum((svdAvailStock - svdVerifiedStock)* svdCostPrice),0)     
   from losstockverificationdetail svd where svdShopId = @intShop and svdId = @intsvId and     
   svdAvailStock > svdVerifiedStock    
  
   select @numSvAddAmt = isnull(sum((svdVerifiedStock - svdAvailStock) * svdCostPrice),0)     
   from losstockverificationdetail svd where svdShopId = @intShop and svdId = @intsvId     
   and svdVerifiedStock > svdAvailStock      
    
   if (@numSvAddAmt > @numSvDeductAmt) or (@numSvAddAmt < @numSvDeductAmt)    
     begin    
    insert into moaJournalHeader (JournalId, CompanyId, JournalDate,     
    referenceno, remarks, financialId, Type, CurrencyId,chequedate, updatetime )    
    values (@intJournalId, @intCompanyId, @dtsvDate, @strsvno,     
    @strRemarks, @intFinancialId, 'ssv', @intcompanycurId, @dtsvDate, @dtutime )    
  
    set @intJournalDetailId = 1    
      
    if (@numSvAddAmt > @numSvDeductAmt)    
      begin    
     -- stock value to be added so debit inventory and credit stockwriteoff acc    
     --debiting hte inventory AccId     
     insert into moaJournalDetails (JournalId,   journaldetailId, CompanyId,     
     JournalCrEDit, AccountId, Amount, ActualAmount,DepAmount, departmentId) values     
     (@intJournalId, @intjournalDetailId,   @intCompanyId, 0, @intInventoryAccId,     
     (@numSvAddAmt - @numSvDeductAmt) * @numConExRate,   (@numSvAddAmt - @numSvDeductAmt),    
     (@numSvAddAmt - @numSvDeductAmt) * @numDepExRate,  @intdepartmentId )     
  
     set @intJournalDetailId = @intJournalDetailId + 1    
    
     -- for converting the amount --->    
     select @intCurrencyId = CurrencyId from aAccountMaster   
     where AccountId = @intSrecAccId    
  
     exec spReturnExRate @intCurrencyId, @strExRates,   @numAccExRate output    
  
     -- get into a variable as expressions cannot be    
     -- passed as parameters of sp         
     set @numTemp = (@numSvAddAmt - @numSvDeductAmt)    
    
     exec spConvertCurrency @numTransEr, @numAccExRate, @numTemp,   @numAaccAmt output    
  
     -- credit the stock writeoff acc Id    
     insert into moaJournalDetails (JournalId,   journaldetailId, CompanyId,     
     JournalCrEDit, accountId, Amount,   actualamount, DepAmount, departmentId) values     
     (@intJournalId, @intjournalDetailId,@intCompanyId, 1, @intsrecAccId,     
     (@numSvAddAmt - @numSvDeductAmt) * @numConExRate,   @numaAccAmt,    
     (@numSvAddAmt - @numSvDeductAmt) * @numDepExRate,  @intdepartmentId )    
      end -- end for more addtion    
     
    if (@numSvAddAmt < @numSvDeductAmt)    
      begin    
     -- stock value to be added so debit inventory and credit stockwriteoff acc    
     -- credit hte inventory AccId     
     insert into moaJournalDetails (JournalId,   journaldetailId, CompanyId,     
     JournalCrEDit, AccountId, Amount,   actualAmount, DepAmount, departmentId) values     
     (@intJournalId, @intJournalDetailId,@intCompanyId, 1, @intInventoryAccId,     
     (@numSvDeductAmt - @numSvAddAmt) * @numConExRate,   (@numSvDeductAmt - @numSvAddAmt),    
     (@numSvDeductAmt - @numSvAddAmt) * @numDepExRate,  @intdepartmentId)     
  
     set @intJournalDetailId = @intJournalDetailId +1    
  
     -- for converting the amount --->    
     select @intCurrencyId = CurrencyId   from aAccountMaster  where AccountId = @intSwoAccId    
  
     exec spReturnExRate @intCurrencyId, @strExRates,   @numAccExRate output    
  
     -- get into a variable as expressions cannot be  passed as parameters of sp         
     set @numTemp = (@numSvDeductAmt - @numSvAddAmt)    
    
     exec spConvertCurrency @numTransEr, @numAccExRate,@numTemp,   @numAaccAmt output    
  
     -- credit the stock writeoff acc Id    
     insert into moaJournalDetails (JournalId,   journaldetailId, CompanyId,     
     JournalCrEDit, accountId, Amount,   actualamount, DepAmount, DepartmentId) values     
     (@intJournalId, @intjournalDetailId,@intCompanyId, 0,   @intswoAccId,     
     (@numSvDeductAmt - @numSvAddAmt) * @numConExRate,   @numaAccAmt,    
     (@numSvDeductAmt - @numSvAddAmt) * @numDepExRate,  @intdepartmentId)    
      end -- end for more addtion    
     end    
    
   update losstockverificationheader  set svhposted = 1 WHERE svhId =     
    @intsvId and svhShopId = @intShop    
  
   set @intJournalId = @intJournalId + 1     
  
    end -- for item rate =0 check     
    
  fetch next FROM  svcur into @intsvId, @strsvno, @dtsvDate, @strRemarks,     
  @dtutime, @intDepartmentId, @numConExRate, @numDepExRate, @strExRates    
   end -- CUR END    
 Close svcur     
 Deallocate svcur     
    
end 




go

------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Sales/Import Analysis GST Seprately (Advanced) report received from bijesh on 10.10.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwSalesImportProdWiseGSTSeparately')
   DROP view dbo.vwSalesImportProdWiseGSTSeparately
GO

  
 -- Last Modified by : Kishore, Hariharan , Hariharan R    
-- Modified on      : 09/05/2003, 14/05/2003, 06/06/2003    
-- Comments         : Added sales date column and removed grouping by    
--                    Month and year (08/03/2003)    
--                    Replaced view vwImportQty with vwPurchaseBillDetail (18/03/2003)    
--      : Given convert function to take the numeric values       
-----------------------------------------------------------------    
-- Replaced with source from v2 on 12/06/2003    
-----------------------------------------------------------------    
-- Modified on      : 18/06/2003    
-- Modified by      : Kishore    
-- Comment          : Added MonthName, MonthNo, YearName columns and other columns    
  
--Modified on       :12-08-09  
--Modified By       :Nidheesh   
--comment           :considered 'Percentage' as negative for RBD case   
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--This View is Created from vwSalesImportProdWise for handling GST seperately
--Created by:Aadyakumar.D.V
--Dated:07/05/2012
----------------------------------------------------------------
  
  --Modified by : Bijesh.B
--Date        : 04-10-2012
--Des         : Bug Fixing-Dept wise GST
----------------------------------------------------------------
--Modified by : Bijesh.B  
--Date        : 06-10-2012  
--Des         : Bug Fixing -wrong values is dispalying in case of exchange and return  
----------------------------------------------------------------  
  
CREATE VIEW vwSalesImportProdWiseGSTSeparately AS      
      
 SELECT c.CategoryNameDescription, i.ItemCode, i.ItemDescription,       
 Margin.ItemId, i.ItemCategoryId,      
 AVG(Margin.ItemUnitPrice) ItemUnitPrice,       
 AVG(Margin.dItemUnitPrice) dItemUnitPrice,       
 AVG(Margin.cItemUnitPrice) cItemUnitPrice,       
 CONVERT(numeric(18,3), SUM(ISNULL(Margin.Quantity, 0))) Quantity,       
 CONVERT(numeric(18,2), sum(Costprice)) CostPrice,       
 CONVERT(numeric(18,2), sum(dCostprice)) dCostPrice,       
 CONVERT(numeric(18,2), sum(cCostprice)) cCostPrice,       
 CONVERT(numeric(18,2), SUM(Margin.Margin)) Margin,       
 CONVERT(numeric(18,2), SUM(Margin.dMargin)) dMargin,       
 CONVERT(numeric(18,2), SUM(Margin.cMargin)) cMargin,     
     
 --convert(numeric(18,2),(SUM(Margin.Margin) * 100) / sum(Costprice) ) Percentage,      
 --SUM(Percentage) Percentage,    
 case when Quantity>0 then SUM(Percentage)else SUM(Percentage)end Percentage,      
 --SUM(dPercentage) dPercentage,    
 case when Quantity>0 then SUM(dPercentage)else SUM(dPercentage)end dPercentage,        
 --SUM(cPercentage) cPercentage,    
 case when Quantity>0 then SUM(cPercentage)else SUM(cPercentage)end cPercentage,          
 CONVERT(numeric(18,3), SUM(ISNULL(Margin.TransQty, 0))) TransQty,      
 SalesDate,   
 sum(Amount) Amount,   
 sum(cAmount) cAmount,   
 sum(dAmount) dAmount,   
 margin.MonthName,   
 margin.MonthNo,  
 margin.YearName ,  
 sum(GST)GST, --aadya      
 sum(dGST)dGST,  
 sum(cGST)cGST  
 FROM      
  (SELECT posdItemId ItemId,      
  ItemUnitPrice, dItemUnitPrice, cItemUnitPrice,      
  Quantity, 0 TransQty, poshBilldate SalesDate,       
  Margin, dMargin, cMargin,      
  Amount, dAmount, cAmount,      
  costprice, dCostPrice, cCostPrice,      
  substring(convert(varchar(4), datename(month, poshbilldate)),1,3) MonthName,       
  month(poshbilldate) MonthNo,    
       
  year(poshbilldate) YearName,      
  Percentage, dPercentage, cPercentage,  
  isnull(GST,0)GST,  --aadya      
  isnull(dGST,0)dGST,  
  isnull(cGST,0)cGST  
  FROM vwSalesMarginAndPercGSTSeparately mp      
     
  UNION ALL      
   
  SELECT pbdItemId ItemId,       
  pbdItemUnitPrice,   
  pbdItemUnitPrice dUnitPrice,   
  pbdItemUnitPrice cUnitPrice,      
  0 Quantity, pbdItemQuantity TransQty, pbhBilldate SalesDate,       
  0 Margin, 0 dMargin, 0 cMargin,      
  0 amount, 0 dAmount, 0 cAmount,      
  0 costprice, 0 dCostPrice, 0 cCostPrice,      
  substring(convert(varchar(4), datename(month, pbhBilldate)), 1, 3) MonthName,       
  month(pbhBillDate) MonthNo,       
  year(pbhBillDate) YearName,      
  0 Percentage, 0 dPercentage, 0 cPercentage   
  ,isnull(pbdItemTaxAmount,0) gst --aadya     
  ,isnull(pbdItemTaxAmount,0) dgst  
  ,isnull(pbdItemTaxAmount,0) cgst  
    
  FROM vwPurchaseBillDetailGSTSeparately iq) Margin, aItem i, aItemCategory c      
 WHERE Margin.ItemId = i.ItemId      
 AND i.ItemCategoryId = c.ItemCategoryId      
 GROUP BY c.CategoryNameDescription, i.ItemCode, i.ItemDescription,       
 Margin.ItemId, i.ItemCategoryId, CostPrice, Margin.SalesDate,       
 margin.yearname, margin.monthname, margin.monthno,Margin.Quantity      
      
go

------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Sales/Import Analysis GST Seprately (Advanced) report received from bijesh on 10.10.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
  
IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwSalesMarginAndPercGSTSeparately')
   DROP view dbo.vwSalesMarginAndPercGSTSeparately
GO
    
-- Modified on          : 12/12/02        
-- Modified by   : leo        
-- Comments  : v3        
----------------------------------------------------------------------------------------        
-- Modified on          : 12/06/2003        
-- Modified by          : Kishore        
-- Comments             : Added amount column        
--                        Added cAmount and dAmount on 18/06/2003        
-- Sebin(24/06/09)-Changed itemunitprice,ditemunitprice & citemUnitPrice,it was taken average before                      
----------------------------------------------------------------------------------------       
-- Modified on  :-12-08-09    
-- Modified by  :Nidheesh     
--Comments :to avoid Divide by zero error 'itemunitprice'is diredctly taken from view vs    
--comments  :included the condition avg(posdunitprice)in MARGIN and PERCENTAGE to consider RBD    
----------------------------------------------------------------------------------------    
--This view is created from vwSalesMarginAndPerc for hadling gst sepepratly
--crated on 07/05/2012
--Created by Aadyakumar.D.V
----------------------------------------------------------------------------------------------------------------------
-- Modified by : Bijesh.B  
-- Date        : 09-10-2012  
-- DEsc        : Correct Margin   
----------------------------------------------------------------------------------------------------------------------  
CREATE VIEW vwSalesMarginAndPercGSTSeparately  AS          
select ic.categorynamedescription, a.itemcode, a.brand, a.modelno, vd.itemdescription,           
posditemid, a.itemcategoryid,         
--sum(amount)/sum(posdquantity)itemunitprice       
vs.posdUnitPrice itemunitprice,       
--sum(dAmount)/sum(posdquantity) ditemunitprice,      
vs.dUnitPrice ditemunitprice,       
--sum(cAmount)/sum(posdquantity) citemunitprice,      
vs.cUnitPrice citemunitprice,            
sum(posdquantity) quantity, poshBilldate, poshShopID,           
AVG(costprice) costprice, AVG(dcostprice) dcostprice, AVG(ccostprice) ccostprice,  
     
--(avg(posdunitprice) - AVG(costprice))Margin          
--(avg(dunitprice) - AVG(dcostprice)) dMargin,      
--(avg(cunitprice) - AVG(ccostprice)) cMargin,            
--case when avg(posdunitprice)=0 then -(avg(posdunitprice) - AVG(costprice))else(avg(posdunitprice) - AVG(costprice))end Margin,        
--case when avg(posdunitprice)=0 then -(avg(dunitprice) - AVG(dcostprice))else(avg(dunitprice) - AVG(dcostprice))end dMargin,              
--case when avg(posdunitprice)=0 then -(avg(cunitprice) - AVG(ccostprice))else(avg(cunitprice) - AVG(ccostprice))end cMargin,              
sum(vs.Margin)Margin,sum(vs.dMargin) dMargin,sum(vs.cMargin) cMargin,  
      
--case when avg(costprice)>0 then (avg(posdunitprice) - AVG(costprice))/AVG(costprice)           
--else (avg(posdunitprice) - AVG(costprice)) end Percentage,           
--case when avg(dcostprice)>0 then (avg(dunitprice) - AVG(dcostprice))/AVG(dcostprice)           
--else (avg(dunitprice) - AVG(dcostprice)) end dPercentage,          
--case when avg(ccostprice)>0 then (avg(cunitprice) - AVG(ccostprice))/AVG(ccostprice)           
--else (avg(cunitprice) - AVG(ccostprice)) end cPercentage,         
  
case when avg(costprice)<>0 then case when avg(posdunitprice)=0 then -(avg(posdunitprice) - AVG(costprice))/AVG(costprice)      
else (avg(posdunitprice) - AVG(costprice))/AVG(costprice)end          
   else (avg(posdunitprice) - AVG(costprice)) end Percentage,     
     
case when avg(dcostprice)<>0 then case when avg(posdunitprice)=0 then -(avg(dunitprice) - AVG(dcostprice))/AVG(dcostprice)      
else (avg(dunitprice) - AVG(dcostprice))/AVG(dcostprice)end               
   else (avg(dunitprice) - AVG(dcostprice)) end dPercentage,          
case when avg(ccostprice)<>0 then case when avg(posdunitprice)=0  then -(avg(cunitprice) - AVG(ccostprice))/AVG(ccostprice)          
else (avg(cunitprice) - AVG(ccostprice))/AVG(ccostprice)end           
  else (avg(cunitprice) - AVG(ccostprice)) end cPercentage,         
   
/*  
(convert(numeric(18,2),(((sum(Amount))-(sum(costprice)))/(sum(Amount)))*100))Percentage,  
(convert(numeric(18,2),(((sum(dAmount))-(sum(dcostprice)))/(sum(dAmount)))*100))dPercentage,  
(convert(numeric(18,2),(((sum(cAmount))-(sum(ccostprice)))/(sum(cAmount)))*100))cPercentage,  
*/  
   
sum(amount) Amount, sum(dAmount) dAmount, sum(cAmount) cAmount,     
sum(GSTAmount) GST, sum(dGSTAmount) dGST, sum(cGSTAmount) cGST          
from vwShopItemSalesGSTSeparately vs, aitem a, vwitemdescription vd,          
aitemcategory ic where vs.posditemid=a.itemid and a.itemid=vd.itemid and          
a.itemcategoryid= ic.itemcategoryid   
group by poshBilldate, poshshopid,           
posditemid, a.itemcategoryid, poshBilldate, ic.categorynamedescription,           
a.itemcode, a.brand, a.modelno,vd.itemdescription,vs.posdUnitPrice,vs.dUnitPrice,vs.cUnitPrice   
  
        
go

------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Sales/Import Analysis GST Seprately (Advanced) report received from bijesh on 10.10.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS(SELECT *  FROM sys.views WHERE name ='vwShopItemSalesGstSeparately')
   DROP view dbo.vwShopItemSalesGstSeparately
GO
  
--Modified on  : 20/12/02                                
--Modified by   : Hariharan R                                
--Comments  : v3                                
--Added reexporting transaction                                
--------------------------------------------------------------------------                                
-- Modified by     : Kishore                                
-- Modified on  : 12/06/2003                                
-- Comments  : Added the aMount, cAmount and dAmount columns                                
--                        (On comparison with v2)                                
--------------------------------------------------------------------------                                
                                
 --------------------------------------------------------------------                                
--Modified on                  : 27/08/2003                                
--Modified by                  : Reji Abraham                                
--Comments                     : Replaced table losserviceheader by losserviceinvheader                                    
--          : and modified fields, previous fields are alias names                                
--          :given ihTransFinised = 1 condition check to pick the confirmed                                
--          :Transactions Only.                                
                                
-------------------------------------------------------------------------------------                                
--Modified on                  : 15/04/04                                
--Modified by                  : venkitesh                                
--Comments                     : Replaced - symbol for goods return case and Given convert for getting accurated figure                              
-------------------------------------------------------------------------------------                                
--Modified on                  : 26/08/08                                
--Modified by                  : Benzigar                                
--Comments                     : Added condition ihNoofOCDetails=0 in specialinvoice to avoid return before despatch items from daily sales                             
--                             : Added case for Direct invoice - return before despatch                            
---------------------------------------------------------------------------------------                        
--Modified on                  : 05/08/09                                
--Modified by                  : Nidheesh                                 
--Comments                     : taken the reqqty as negative in the case of RBD of (4  Direct invoice - return before despatch )                             
-- : removed the minus sign of unitprice,margin                 
---------------------------------------------------------------------------------------              
--Modified on                  : 23/10/09                    
--Modified by                  : Nidheesh                    
--Comments                     : Included the requiremnet of adding custom price to cost price for shop credit invoice.(case-2)                  
--                             : checked whether the shop is BondedWareHouse or not and  'AddCustomDutyToCostPrice'.               
---------------------------------------------------------------------------------------                        
--Modified on                  : 10/11/09                                
--Modified by                  : Regin                
--Comments                     : To get the margin of sale correctly modified the margin portion                 
---------------------------------------------------------------------------------------                        
--Modified on                  : 10/11/09      
--Modified by                  : Regin                
--Comments : In Goods Exchange part, sedquantity was replaced by sedExchangeQty since sedExchangeQty is the returned qty                
---------------------------------------------------------------------------------------                        
--Modified on                  : 05/12/2009              
--Modified by                  : Benzigar                
--Comments                     : In invoice part added case condition to handle divided by 0 problem               
---------------------------------------------------------------------------------------                        
--Modified on                  : 07/08/2010                
--Modified by                  : Sreejith G A                
--Comments                     : Added an additional field Actual Price of the item from Transaction table           
---------------------------------------------------------------------------------------                        
--Modified on                  : 17/11/2010                
--Modified by                  : Abhishek CS               
--Comments                     : customerid added for koddoo salesanalysisbyitem(actual)report need to filter by customer        
---------------------------------------------------------------------------------------                        
--Modified on                  : 19/05/2011                
--Modified by                  : Aadyakumar.D.V               
--Comments                     : FRS-409830,divide by zero errror       
---------------------------------------------------------------------------------------                        
--Modified on                  : 18/06/2011                
--Modified by                  : Nidheesh P V             
--Comments                     : Added ELSE part in the checking of wheather quantity is zero or not.    
--Modified Area       : All reports which are showing sales of items.    
--Reference        : RefNo:1    
---------------------------------------------------------------------------------------           
  
--------------------------------------------------------------------------     
--Created on                   : 20/04/2012            
--Comments                     : New view created for sonee (copy of spSalesAnalysisByItem)  
--                               for new report rptSalesByItemShopwiseGSTSeparately.rpt  
-- Tikect id                   : JDJ-400367 (Sonee)  
---------------------------------------------------------------------------------------------     
--Modified by   : Bijesh.B 
--Date          : 16/07/2012
--Ticket id     : JDJ-400367 
--Desc          : correctd values
----------------------------------------------------------------------------------------------       
--Modified by   : Bijesh.B 
--Date          : 01/10/2012
--Ticket id     : JDJ-400367 
--Desc          : correctd Gst Amount in case of goods exchange
----------------------------------------------------------------------------------------------       
--Modified by   : Bijesh.B   
--Date          : 06/10/2012  
--Ticket id     : JDJ-400367   
--Desc          : correctd Margin in case of Exchange  
----------------------------------------------------------------------------------------------         
--Modified by   : Bijesh.B   
--Date          : 09/10/2012  
--Ticket id     : JDJ-400367   
--Desc          : correctd Margin - After doing exchange and return  
----------------------------------------------------------------------------------------------         
    
CREATE VIEW [dbo].[vwShopItemSalesGstSeparately] AS                                  
-- 1                                  
select                         
 posditemid,            
 convert(numeric(18,8), posdActualUnitPrice *  poshExchangeRate) cActualUnitPrice,  --sree                       
 convert(numeric(18,8), posdActualUnitPrice *  poshDepExRate) dActualUnitPrice,   --sree                
 convert(numeric(18,8), posdActualUnitPrice) ActualUnitPrice,  --sree                
 --convert(numeric(18,8), (posdUnitPrice /CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END) *  poshExchangeRate) cUnitPrice,   --RefNo:1                      
 --convert(numeric(18,8), (posdUnitPrice / CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END) *  poshDepExRate) dUnitPrice,     --RefNo:1                     
 --convert(numeric(18,8), (posdUnitPrice / CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END)) posdUnitPrice,                --RefNo:1       
 convert(numeric(18,8), ((posdUnitPrice/CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END)-(isnull(posdItemTaxAmount,0)/CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END))  *  poshExchangeRate) cUnitPrice,   --RefNo:1                     
 convert(numeric(18,8), ((posdUnitPrice/CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END)-(isnull(posdItemTaxAmount,0)/CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END)) *  poshDepExRate) dUnitPrice,     --RefNo:1                     
 convert(numeric(18,8), (posdUnitPrice/CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END)-(isnull(posdItemTaxAmount,0)/CASE WHEN posdquantity=0 THEN 1 ELSE posdquantity END)) posdUnitPrice,                   --RefNo:1       
 posdquantity,posdRateType, poshBilldate,poshbillID,                        
 poshBillNo,poshShopID,   
  
-- posdcostprice costprice,   
 --posdcostprice * poshDepExRate dcostprice,                         
 --posdcostprice * poshExchangeRate ccostprice,   
 (posdcostprice*posdquantity) costprice,   
 (posdcostprice*posdquantity) * poshDepExRate dcostprice,                         
 (posdcostprice*posdquantity) * poshExchangeRate ccostprice,   
   
 'S' as type,                         
-- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                  
-- ((posdUnitPrice / posdquantity) - posdcostprice) margin,                      
-- ((posdUnitPrice / posdquantity) - posdcostprice) * poshDepExRate  dmargin,                         
-- ((posdUnitPrice / posdquantity) - posdcostprice) * poshExchangeRate  cmargin,                         
    
 -- posdUnitPrice-posdcostprice*posdquantity margin,                         
 --(posdUnitPrice-posdcostprice*posdquantity)* poshDepExRate dmargin,                         
 --(posdUnitPrice-posdcostprice*posdquantity)* poshExchangeRate cmargin,                         
    
 -- (posdUnitPrice-isnull(posdItemTaxAmount,0))-posdcostprice*posdquantity margin,                         
 --(((posdUnitPrice-isnull(posdItemTaxAmount,0))-posdcostprice*posdquantity))* poshDepExRate dmargin,                         
 --(((posdUnitPrice-isnull(posdItemTaxAmount,0))-posdcostprice*posdquantity))* poshExchangeRate cmargin,       
 (convert(numeric(18,8),((posdunitprice-isnull(posdItemTaxAmount,0)))))  
  - (posdcostprice*posdquantity) margin,    
   (convert(numeric(18,8),((posdunitprice-isnull(posdItemTaxAmount,0)))) * poshdepexrate) -                     
        (posdcostprice*posdquantity) * poshdepexrate dmargin,    
   (convert(numeric(18,8),((posdunitprice-isnull(posdItemTaxAmount,0))) * poshexchangerate)) -    
        (posdcostprice*posdquantity) * poshexchangerate cmargin,                     
     
                     
     
 --convert(numeric(18,8),posdUnitPrice) Amount,    
 --convert(numeric(18,8),posdUnitPrice * poshExchangeRate) cAmount,                        
 --convert(numeric(18,8),posdUnitPrice * poshDepExRate) dAmount ,            
 convert(numeric(18,8),(posdUnitPrice-isnull(posdItemTaxAmount,0))) Amount,    
 convert(numeric(18,8),(posdUnitPrice-isnull(posdItemTaxAmount,0)) * poshExchangeRate) cAmount,                        
 convert(numeric(18,8),(posdUnitPrice-isnull(posdItemTaxAmount,0)) * poshDepExRate) dAmount ,            
    
 convert(numeric(18,8),posdActualUnitPrice * posdquantity) ActualAmount,--sree            
 convert(numeric(18,8),posdActualUnitPrice * poshExchangeRate *posdquantity) cActualAmount,  --sree                      
 convert(numeric(18,8),posdActualUnitPrice * poshDepExRate *posdquantity) dActualAmount,     --sree                   
 poshcustomerid,    
 convert(numeric(18,8),(isnull(posdItemTaxAmount,0)))GSTAmount,    
 convert(numeric(18,8),(isnull(posdItemTaxAmount,0))* poshdepexrate)dGSTAmount,    
 convert(numeric(18,8),(isnull(posdItemTaxAmount,0))* poshexchangerate)cGSTAmount    
from                         
 losposdetail, losposheader                         
where     
 poshBillid = posdBillid and poshShopid = posdshopid AND POSHCANCELLED = 0                  
                                   
union all                                  
---- 2                                   
--select                                   
-- iditemid, convert(numeric(18,8),                                   
-- (idUnitPrice / idquantity)  *  ihExchangeRate) cUnitPrice,                                   
-- convert(numeric(18,8), (idUnitPrice / idquantity)  *  ihDepExRate) dUnitPrice,                                   
-- convert(numeric(18,8), (idUnitPrice / idquantity))  posdUnitPrice,                                   
-- idquantity, idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid,idcostprice,                     
-- idcostprice * ihDepExRate,idcostprice * ihExchangeRate, 'S',                                  
-- -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                
-- -- ((idUnitPrice / idquantity) * ihExchangeRate - idcostprice) margin,                                   
-- -- ((idUnitPrice / idquantity) - idcostprice) * ihDepExRate  dmargin,                                  
-- -- ((idUnitPrice / idquantity) - idcostprice) * ihExchangeRate cmargin,                                     
-- idUnitPrice-idcostprice*idquantity margin,                                   
-- (idUnitPrice-idcostprice*idquantity) * ihDepExRate  dmargin,                                  
-- (idUnitPrice-idcostprice*idquantity) * ihExchangeRate cmargin,                                     
-- convert(numeric(18,8),idUnitPrice) Amount,convert(numeric(18,8),idUnitPrice * ihExchangeRate) cAmount,                          
-- convert(numeric(18,8),idUnitPrice * ihDepExRate) dAmount                                  
--from                                   
-- losinvoiceheader ih, losinvoicedetail invd                                   
--                                  
--where                                   
-- ih.ihInvoiceid = invd.idInvoiceid  and ih.ihshopid = invd.idshopid AND                                  
-- IHCANCELLED = 0 and ihproforma = 0 and ihtype = 'i'                                  
            
-- 2  shop credit invoice                               
select                       
 iditemid,            
 convert(numeric(18,8), idActualUnitPrice *  ihexchangerate) cActualUnitPrice,  --sree                       
 convert(numeric(18,8), idActualUnitPrice *  ihDepExRate) dActualUnitPrice,   --sree                
 convert(numeric(18,8), idActualUnitPrice) ActualUnitPrice,  --sree             
 --case when (idquantity<>0) then  convert(numeric(18,8),(idUnitPrice / CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)  *  ihExchangeRate) else 0 end  cUnitPrice,   --RefNo:1                           
 --case when (idquantity<>0) then convert(numeric(18,8),(idUnitPrice / CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)  *  ihDepExRate) else 0 end dUnitPrice,       --RefNo:1             
 --case when (idquantity<>0) then (idUnitPrice / CASE WHEN idquantity=0 THEN 1 ELSE idquantity END) else 0 end posdUnitPrice,                                           --RefNo:1       
    
 case when (idquantity<>0) then convert(numeric(18,8),((idUnitPrice / CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)-(isnull(idItemTaxAmount,0)/CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)) *  ihExchangeRate) else 0 end  cUnitPrice,   --RefNo:1
  
    
  
 case when (idquantity<>0) then convert(numeric(18,8),((idUnitPrice / CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)-(isnull(idItemTaxAmount,0)/CASE WHEN idquantity=0 THEN 1 ELSE idquantity END))  *  ihDepExRate) else 0 end dUnitPrice,       --RefNo:1
  
    
  
 case when (idquantity<>0) then convert(numeric(18,8),(idUnitPrice / CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)-(isnull(idItemTaxAmount,0)/CASE WHEN idquantity=0 THEN 1 ELSE idquantity END)) else 0 end posdUnitPrice,                               
  
  
  
--RefNo:1       
 idquantity, idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid,                
 case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then idcostprice+(idcostprice*m.CustomCategoryPercent/100) else idcostprice end  idcostprice,                       
 case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then (idcostprice * ihDepExRate)+((idcostprice * ihDepExRate)*m.CustomCategoryPercent/100) else idcostprice * ihDepExRate end ,                
 case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then (idcostprice * ihExchangeRate)+((idcostprice * ihExchangeRate)*m.CustomCategoryPercent/100) else idcostprice * ihExchangeRate end ,'S',                      
                
-- case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then ((idUnitPrice / idquantity) * ihExchangeRate - (idcostprice+(idcostprice*m.CustomCategoryPercent/100))) else((idUnitPrice / idquantity) * ihExchangeRate - idcostprice)end margin,          
  
  
  
-- case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then ((idUnitPrice / idquantity) - (idcostprice+(idcostprice*m.CustomCategoryPercent/100))) * ihDepExRate else((idUnitPrice / idquantity) - idcostprice) * ihDepExRate end dmargin,              
  
  
  
-- case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then ((idUnitPrice / idquantity) - (idcostprice+(idcostprice*m.CustomCategoryPercent/100))) * ihExchangeRate else((idUnitPrice / idquantity) - idcostprice) * ihExchangeRate end cmargin,        
  
  
  
        
 --case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then idUnitPrice-(idcostprice+(idcostprice*m.CustomCategoryPercent/100))*idquantity else(idUnitPrice-idcostprice*idquantity)end margin,                       
 --case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then (idUnitPrice-(idcostprice+(idcostprice*m.CustomCategoryPercent/100))*idquantity) * ihDepExRate else(idUnitPrice-idcostprice*idquantity) * ihDepExRate end dmargin,                      
 --case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then (idUnitPrice-(idcostprice+(idcostprice*m.CustomCategoryPercent/100))*idquantity) * ihExchangeRate else(idUnitPrice-idcostprice*idquantity) * ihExchangeRate end cmargin,                    
  
  
  
  
 case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then (idUnitPrice- isnull(idItemTaxAmount,0))-(idcostprice+(idcostprice*m.CustomCategoryPercent/100))*idquantity                      
   else((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*idquantity)end margin,                       
 case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then ((idUnitPrice-isnull(idItemTaxAmount,0))-(idcostprice+(idcostprice*m.CustomCategoryPercent/100))*idquantity) * ihDepExRate      
  else((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*idquantity) * ihDepExRate end dmargin,                      
 case when futurevarchar='B' and AddCustomDutyToCostPrice=1 then ((idUnitPrice-isnull(idItemTaxAmount,0)) -(idcostprice+(idcostprice*m.CustomCategoryPercent/100))*idquantity) * ihExchangeRate   
 else((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*idquantity) * ihExchangeRate end cmargin,                      --convert(numeric(18,8),idUnitPrice) Amount,    
 --convert(numeric(18,8),idUnitPrice * ihExchangeRate) cAmount,                      
 --convert(numeric(18,8),idUnitPrice * ihDepExRate) dAmount,           
 convert(numeric(18,8),idUnitPrice-isnull(idItemTaxAmount,0))Amount,    
 convert(numeric(18,8),(idUnitPrice-isnull(idItemTaxAmount,0))* ihExchangeRate) cAmount,                      
 convert(numeric(18,8),(idUnitPrice-isnull(idItemTaxAmount,0))* ihDepExRate) dAmount,             
     
 convert(numeric(18,8),idActualUnitPrice * idquantity) ActualAmount,--sree            
 convert(numeric(18,8),idActualUnitPrice * ihexchangerate *idquantity) cActualAmount,  --sree                      
 convert(numeric(18,8),idActualUnitPrice * ihDepExRate *idquantity) dActualAmount,     --sree                      
 ih.ihCustomerID,    
     
 convert(numeric(18,8),(isnull(idItemTaxAmount,0)))GSTAmount,    
 convert(numeric(18,8),(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,    
 convert(numeric(18,8),(isnull(idItemTaxAmount,0))* ihexchangerate)cGSTAmount    
from                       
 losinvoiceheader ih, losinvoicedetail invd                 
 LEFT OUTER JOIN aItem a ON  a.ItemID=iditemid                
 LEFT OUTER JOIN acustomsmaster m ON  m.CustomID=a.CustomID                
 ,ashops                   
where                       
 ih.ihInvoiceid = invd.idInvoiceid  and ih.ihshopid = invd.idshopid AND                      
 IHCANCELLED = 0 and ihproforma = 0 and ihtype = 'i' and ihcashinvoice=0                 
  and ih.ihShopID=shopid                   
                                  
union all                                  
--3                                  
select                                   
 seditemid,                
 convert(numeric(18,8), sedActualUnitPrice *  sehExchangeRate) cActualUnitPrice,  --sree                       
 convert(numeric(18,8), sedActualUnitPrice *  sehDepExRate) dActualUnitPrice,   --sree                
 convert(numeric(18,8), sedActualUnitPrice) ActualUnitPrice,  --sree                                
 --convert(numeric(18,8),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehExchangeRate) cUnitPrice,   --RefNo:1                                 
 --convert(numeric(18,8),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehDepExRate) dUnitPrice,      --RefNo:1                             
 --convert(numeric(18,8),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) ) UnitPrice,                     --RefNo:1               
convert(numeric(18,8),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END)-(isnull(sedItemTaxAmount,0)/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehExchangeRate) cUnitPrice,   --RefNo:1                                 
convert(numeric(18,8),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END)-(isnull(sedItemTaxAmount,0)/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehDepExRate) dUnitPrice,      --RefNo:1                             
convert(numeric(18,8),(sedUnitPrice / CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END)-(isnull(sedItemTaxAmount,0)/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END)) UnitPrice,                     --RefNo:1               
    
/*    
 convert(numeric(18,8),((sedUnitPrice-(isnull(sedItemTaxAmount,0)/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END))/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehExchangeRate) cUnitPrice,   --RefNo:1                                 
 convert(numeric(18,8),((sedUnitPrice-(isnull(sedItemTaxAmount,0)/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END))/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) * sehDepExRate) dUnitPrice,      --RefNo:1                             
 convert(numeric(18,8),((sedUnitPrice-(isnull(sedItemTaxAmount,0)/CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END)) /CASE WHEN sedquantity=0 THEN 1 ELSE sedquantity END) ) UnitPrice,                     --RefNo:1               
*/    
    
 sedquantity, sedRateType,sehExchangeDate,sehExchangeID,sehExchangeNo,sehShopID,         
 sedcostprice, sedcostprice *  sehDepExRate, sedcostprice * sehExchangeRate, 'S',                                  
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                  
 -- ((sedUnitPrice / sedquantity)  - sedcostprice) margin,                                  
 -- ((sedUnitPrice / sedquantity) - sedcostprice) *  sehDepExRate  dmargin,                                  
 -- ((sedUnitPrice / sedquantity) - sedcostprice) *  sehExchangeRate  cmargin,                                  
 -- sedUnitPrice-sedcostprice*sedquantity margin,                                  
 --(sedUnitPrice-sedcostprice*sedquantity) *  sehDepExRate  dmargin,                                  
 --(sedUnitPrice-sedcostprice*sedquantity) *  sehExchangeRate  cmargin,                    
  (sedUnitPrice-isnull(sedItemTaxAmount,0))-sedcostprice*sedquantity margin,                                  
 ((sedUnitPrice-isnull(sedItemTaxAmount,0))-sedcostprice*sedquantity) *  sehDepExRate  dmargin,                                  
 ((sedUnitPrice-isnull(sedItemTaxAmount,0))-sedcostprice*sedquantity) *  sehExchangeRate  cmargin,                                  
     
 --convert(numeric(18,8),sedUnitPrice)  Amount,    
 --convert(numeric(18,8),sedUnitPrice * sehExchangeRate) cAmount,                                  
 --convert(numeric(18,8),sedUnitPrice * sehDepExRate) dAmount,            
 convert(numeric(18,8),sedUnitPrice-isnull(sedItemTaxAmount,0))  Amount,    
 convert(numeric(18,8),(sedUnitPrice-isnull(sedItemTaxAmount,0)) * sehExchangeRate) cAmount,                                  
 convert(numeric(18,8),(sedUnitPrice-isnull(sedItemTaxAmount,0)) * sehDepExRate) dAmount,            
      
 convert(numeric(18,8),sedActualUnitPrice * sedquantity) ActualAmount,--sree            
 convert(numeric(18,8),sedActualUnitPrice * sehExchangeRate *sedquantity) cActualAmount,  --sree                      
 convert(numeric(18,8),sedActualUnitPrice * sehDepExRate *sedquantity) dActualAmount,     --sree                                  
 0,    
convert(numeric(18,8),(isnull(sedItemTaxAmount,0)))GSTAmount    
,convert(numeric(18,8),(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,    
convert(numeric(18,8),(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount          
from                 
 losposexchangeheader,losposexchangedetail                                   
where                                   
 sedExchangeid = sehExchangeID and sedShopID = sehShopid and                                   
 SEHCANCELLED = 0 and sedbillorexchange  = 'E'                                  
                                   
union all                                  
-- 4                                   
select                                   
 iditemid,             
 convert(numeric(18,8), idActualUnitPrice *  ihExchangeRate) cActualUnitPrice,  --sree                       
 convert(numeric(18,8), idActualUnitPrice *  ihDepExRate) dActualUnitPrice,   --sree                
 convert(numeric(18,8), idActualUnitPrice) ActualUnitPrice,  --sree             
 --convert(numeric(18,8),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,   --RefNo:1                                  
 --convert(numeric(18,8),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,      --RefNo:1                    
 --convert(numeric(18,8),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)) UnitPrice ,reqqty,               --RefNo:1                     
 convert(numeric(18,8),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,   --RefNo:1                                  
 convert(numeric(18,8),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,      --RefNo:1                    
 convert(numeric(18,8),(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)) UnitPrice ,reqqty,               --RefNo:1                     
 idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,                                   
 idcostprice * ihDepExRate, idcostprice * ihExchangeRate, 'S',                                   
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                  
 -- ((idUnitPrice / reqqty) -idcostprice) margin,                                   
 -- ((idUnitPrice / reqqty)  -idcostprice) *  ihDepExRate dmargin ,                                  
 -- ((idUnitPrice / reqqty)  -idcostprice) *  ihExchangeRate cmargin,                                   
     
-- idUnitPrice- idcostprice*reqqty margin,                                   
 --(idUnitPrice- idcostprice*reqqty) *  ihDepExRate dmargin ,                                  
 --(idUnitPrice- idcostprice*reqqty) *  ihExchangeRate cmargin,                                   
 (idUnitPrice-isnull(idItemTaxAmount,0))- idcostprice*reqqty margin,                                   
 ((idUnitPrice-isnull(idItemTaxAmount,0))- idcostprice*reqqty) *  ihDepExRate dmargin ,                                  
 ((idUnitPrice-isnull(idItemTaxAmount,0))- idcostprice*reqqty) *  ihExchangeRate cmargin,                                   
     
 --convert(numeric(18,8),idUnitPrice) Amount,    
 --convert(numeric(18,8),idUnitPrice * ihExchangeRate)  cAmount,                       
 --convert(numeric(18,8),idUnitPrice * ihDepExRate)  Amount,            
 convert(numeric(18,8),idUnitPrice-isnull(idItemTaxAmount,0)) Amount,    
 convert(numeric(18,8),(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate)  cAmount,                                   
 convert(numeric(18,8),(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate)  Amount,            
     
 convert(numeric(18,8),idActualUnitPrice * reqqty) ActualAmount,--sree            
 convert(numeric(18,8),idActualUnitPrice * ihExchangeRate *reqqty) cActualAmount,  --sree                      
 convert(numeric(18,8),idActualUnitPrice * ihDepExRate *reqqty) dActualAmount,     --sree            
 IhCustomerID,    
 convert(numeric(18,8),(isnull(idItemTaxAmount,0)))GSTAmount    
,convert(numeric(18,8),(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,    
 convert(numeric(18,8),(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount                             
from                                   
 losspecialinvoicedetail, losspecialinvoiceheader                                   
where                                   
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND                                
 IHCANCELLED = 0 and idratetype = 0 and ihproforma = 0                                  
 and IhTransFinished = 1 and ihNoofOCDetails=0                              
                               
union all                                  
-- 4  Direct invoice - return before despatch                      
select                                   
 iditemid,             
 convert(numeric(18,8), idActualUnitPrice *  ihExchangeRate) cActualUnitPrice,  --sree                       
 convert(numeric(18,8), idActualUnitPrice *  ihDepExRate) dActualUnitPrice,   --sree                
 convert(numeric(18,8), idActualUnitPrice) ActualUnitPrice,  --sree             
 --convert(numeric(18,8), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,            --RefNo:1                        
 --convert(numeric(18,8), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,               --RefNo:1                     
 --convert(numeric(18,8), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) UnitPrice,-reqqty,     --RefNo:1                               
 convert(numeric(18,8), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,            --RefNo:1                        
 convert(numeric(18,8), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,               --RefNo:1                     
 convert(numeric(18,8), (idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) UnitPrice,-reqqty,     --RefNo:1                               
     
 idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,                                   
 idcostprice * ihDepExRate, idcostprice * ihExchangeRate, 'R',                                  
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                  
 -- ((idUnitPrice / reqqty) - idcostprice) margin,                                   
 -- ((idUnitPrice / reqqty) - idcostprice) *  ihDepExRate  dmargin ,                                   
 -- ((idUnitPrice / reqqty)  - idcostprice) *  ihExchangeRate cmargin,                                   
     
 -- idUnitPrice-idcostprice*reqqty margin,                                   
 --(idUnitPrice-idcostprice*reqqty) *  ihDepExRate  dmargin ,                                   
 --(idUnitPrice-idcostprice*reqqty) *  ihExchangeRate cmargin,                                   
 -(idUnitPrice-isnull(idItemTaxAmount,0)) -idcostprice*reqqty margin,                    
 -((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*reqqty) *  ihDepExRate  dmargin ,           
 -((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*reqqty) *  ihExchangeRate cmargin,      
     
 --convert(numeric(18,8),-idUnitPrice) Amount,    
 --convert(numeric(18,8),-idUnitPrice * ihExchangeRate) cAmount,                                   
 --convert(numeric(18,8),-idUnitPrice * ihDepExRate) dAmount,            
 convert(numeric(18,8),-(idUnitPrice-isnull(idItemTaxAmount,0))) Amount,    
 convert(numeric(18,8),-(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) cAmount,                                   
 convert(numeric(18,8),-(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dAmount,     
    
 convert(numeric(18,8),-idActualUnitPrice * reqqty) ActualAmount,--sree            
 convert(numeric(18,8),-idActualUnitPrice * ihExchangeRate *reqqty) cActualAmount,  --sree                      
 convert(numeric(18,8),-idActualUnitPrice * ihDepExRate *reqqty) dActualAmount,     --sree            
 IhCustomerID,    
 convert(numeric(18,8),-(isnull(idItemTaxAmount,0)))GSTAmount    
,convert(numeric(18,8),-(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,    
 convert(numeric(18,8),-(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount                             
from                                   
 losspecialinvoicedetail,losspecialinvoiceheader                                  
where                                   
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                   
 idratetype = 0 and ihproforma = 0 and ihTransFinished = 1 and ihNoofOCDetails<>0                              
                 
union all                                  
-- 5                      
-- sedquantity was replaced by sedExchangeQty since sedExchangeQty is the returned qty                   
-- by Regin on 10-11-2009                               
/*                  
select                                   
 seditemid, convert(numeric(18,8), -(sedUnitPrice / sedquantity)  *  sehExchangeRate) cUnitPrice ,                                  
 convert(numeric(18,8), -(sedUnitPrice / sedquantity)  *  sehDepExRate) dUnitPrice,                                   
 convert(numeric(18,8), -(sedUnitPrice / sedquantity)) UnitPrice,                                   
 -sedExchangeQty, sedRateType,sehExchangeDate,sehExchangeID,sehExchangeNo,                                   
 sehShopID, sedcostprice, sedcostprice * sehDepExRate, sedcostprice * sehExchangeRate, 'R' ,                                   
  -(sedUnitPrice-sedcostprice*sedquantity) margin,                                   
  -(sedUnitPrice-sedcostprice*sedquantity) *  sehDepExRate  dmargin,                                  
  -(sedUnitPrice-sedcostprice*sedquantity) *  sehExchangeRate cmargin,                     convert(numeric(18,8),- sedUnitPrice) Amount,                                  
 convert(numeric(18,8),- sedUnitPrice * sehexchangerate)  cAmount,                                  
 convert(numeric(18,8),- sedUnitPrice * sehDepExRate)  dAmount                                  
from                                   
 losposexchangeheader, losposexchangedetail                                   
where           
 sedExchangeid = sehExchangeID and sedShopID = sehShopid and                                   
 SEHCANCELLED = 0 and sedbillorexchange  =  'B' and sedexchangeqty>0                                  
*/            
    
select                                   
 seditemid,             
 convert(numeric(18,8), sedActualUnitPrice *  sehExchangeRate) cActualUnitPrice,  --sree                       
 convert(numeric(18,8), sedActualUnitPrice *  sehDepExRate) dActualUnitPrice,   --sree                
 convert(numeric(18,8), sedActualUnitPrice) ActualUnitPrice,  --sree             
 --convert(numeric(18,8), -(sedUnitPrice / CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)  *  sehExchangeRate) cUnitPrice , --RefNo:1                      
 --convert(numeric(18,8), -(sedUnitPrice / CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)  *  sehDepExRate) dUnitPrice,       --RefNo:1                             
 --convert(numeric(18,8), -(sedUnitPrice / CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)) UnitPrice,                         --RefNo:1           
 convert(numeric(18,8), -((sedUnitPrice/CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END) -(isnull(sedItemTaxAmount,0))/CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)  *  sehExchangeRate) cUnitPrice ,   --RefNo:1                     
  
  
  
 convert(numeric(18,8), -((sedUnitPrice/CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END) -(isnull(sedItemTaxAmount,0))/CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)  *  sehDepExRate) dUnitPrice,       --RefNo:1                      
  
  
  
 convert(numeric(18,8), -((sedUnitPrice/CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END) -(isnull(sedItemTaxAmount,0))/CASE WHEN sedExchangeQty=0 THEN 1 ELSE sedExchangeQty END)) UnitPrice,                         --RefNo:1           
 -sedExchangeQty sedExchangeQty, sedRateType,sehExchangeDate poshbilldate,sehExchangeID,sehExchangeNo,                                   
 sehShopID poshShopID,  
  -(sedcostprice * sedExchangeQty),  
  -((sedcostprice* sedExchangeQty) * sehDepExRate) dcostprice,   
  -((sedcostprice* sedExchangeQty) * sehExchangeRate) ccostprice, 'R' typ ,                                   
  
 -- - sedcostprice,  
 -- -(sedcostprice * sehDepExRate) dcostprice,   
 -- -(sedcostprice* sehExchangeRate) ccostprice, 'R' typ ,                                   
 -- -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                  
 -- -((sedUnitPrice / sedquantity) - sedcostprice) margin,                                   
 -- -((sedUnitPrice / sedquantity) - sedcostprice) *  sehDepExRate  dmargin,                                  
 -- -((sedUnitPrice / sedquantity)  - sedcostprice) *  sehExchangeRate cmargin,                                  
 - --(sedUnitPrice-sedcostprice*sedExchangeQty) margin,                                   
 - --(sedUnitPrice-sedcostprice*sedExchangeQty) *  sehDepExRate  dmargin,                                  
 - --(sedUnitPrice-sedcostprice*sedExchangeQty) *  sehExchangeRate cmargin,                                  
   
 -- -((sedUnitPrice-isnull(sedItemTaxAmount,0))-sedcostprice*sedExchangeQty) margin,                                   
 -- -((sedUnitPrice-isnull(sedItemTaxAmount,0))-sedcostprice*sedExchangeQty) *  sehDepExRate  dmargin,                                  
 -- -((sedUnitPrice-isnull(sedItemTaxAmount,0))-sedcostprice*sedExchangeQty) *  sehExchangeRate cmargin,                                  
  -(convert(numeric(18,8), ((sedunitprice-isnull(sedItemTaxAmount,0)))) -     
           (sedcostprice * sedExchangeQty)) margin,    
    -(convert(numeric(18,8), ((sedunitprice-isnull(sedItemTaxAmount,0)))) -                     
        (sedcostprice * sedExchangeQty)) * sehdepexrate dmargin,    
    -(convert(numeric(18,8), ((sedunitprice-isnull(sedItemTaxAmount,0)))) -     
        (sedcostprice * sedExchangeQty)) * sehexchangerate cmargin,                     
   
 --convert(numeric(18,8),- sedUnitPrice) Amount,                                  
 --convert(numeric(18,8),- sedUnitPrice * sehexchangerate)  cAmount,                                  
 --convert(numeric(18,8),- sedUnitPrice * sehDepExRate)  dAmount ,            
 convert(numeric(18,8),- (sedUnitPrice-isnull(sedItemTaxAmount,0))) Amount,                                  
 convert(numeric(18,8),- (sedUnitPrice-isnull(sedItemTaxAmount,0)) * sehexchangerate)  cAmount,                                  
 convert(numeric(18,8),- (sedUnitPrice-isnull(sedItemTaxAmount,0)) * sehDepExRate)  dAmount ,            
     
 convert(numeric(18,8),-sedActualUnitPrice * sedExchangeQty) ActualAmount,--sree            
 convert(numeric(18,8),-sedActualUnitPrice * sehExchangeRate *sedExchangeQty) cActualAmount,  --sree                      
 convert(numeric(18,8),-sedActualUnitPrice * sehDepExRate *sedExchangeQty) dActualAmount ,    --sree              
 0,        
convert(numeric(18,8),-(isnull(sedItemTaxAmount,0)))GSTAmount    
,convert(numeric(18,8),-(isnull(sedItemTaxAmount,0))* sehdepexrate)dGSTAmount,    
convert(numeric(18,8),-(isnull(sedItemTaxAmount,0))* sehexchangerate)cGSTAmount          
from                                   
 losposexchangeheader, losposexchangedetail                                   
where                                   
 sedExchangeid = sehExchangeID and sedShopID = sehShopid and                                   
 SEHCANCELLED = 0 and sedbillorexchange  =  'B' and sedexchangeqty>0                   
  
                
union all                                  
-- 6                                  
-- Special invoice return                                  
select                                   
 iditemid,             
 convert(numeric(18,8), idActualUnitPrice *  ihExchangeRate) cActualUnitPrice,  --sree                       
 convert(numeric(18,8), idActualUnitPrice *  ihDepExRate) dActualUnitPrice,   --sree                
 convert(numeric(18,8), idActualUnitPrice) ActualUnitPrice,  --sree            
 --convert(numeric(18,8), -(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,     --RefNo:1                               
 --convert(numeric(18,8), -(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,      --RefNo:1                           
 --convert(numeric(18,8), -(idUnitPrice / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) UnitPrice, reqqty,  --RefNo:1                                  
 convert(numeric(18,8), -((idUnitPrice/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)) / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) cUnitPrice,     --RefNo:1                               
 convert(numeric(18,8), -((idUnitPrice/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)) / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihDepExRate) dUnitPrice,         --RefNo:1                           
 convert(numeric(18,8), -((idUnitPrice/CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)-(isnull(idItemTaxAmount,0)) / CASE WHEN reqqty=0 THEN 1 ELSE reqqty END)  *  ihExchangeRate) UnitPrice, reqqty,  --RefNo:1                                  
     
 idRateType,ihInvoicedate,ihInvoiceID, ihInvoiceNo,IhShopid, idcostprice,                                   
 idcostprice * ihDepExRate, idcostprice * ihExchangeRate, 'R',                                  
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                  
 -- -((idUnitPrice / reqqty) - idcostprice) margin,                     
 -- -((idUnitPrice / reqqty) - idcostprice) *  ihDepExRate  dmargin ,                                   
 -- -((idUnitPrice / reqqty)  - idcostprice) *  ihExchangeRate cmargin,                                   
     
 -- -(idUnitPrice-idcostprice*reqqty) margin,                                   
 -- -(idUnitPrice-idcostprice*reqqty) *  ihDepExRate  dmargin ,                                   
 -- -(idUnitPrice-idcostprice*reqqty) *  ihExchangeRate cmargin,                                   
 -((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*reqqty) margin,                                   
 -((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*reqqty) *  ihDepExRate  dmargin ,                                   
 -((idUnitPrice-isnull(idItemTaxAmount,0))-idcostprice*reqqty) *  ihExchangeRate cmargin,                                   
     
 --convert(numeric(18,8),-idUnitPrice) Amount,     
 --convert(numeric(18,8),-idUnitPrice * ihExchangeRate) cAmount,                                   
 --convert(numeric(18,8),-idUnitPrice * ihDepExRate) dAmount,            
 convert(numeric(18,8),-(idUnitPrice-isnull(idItemTaxAmount,0))) Amount,     
 convert(numeric(18,8),-(idUnitPrice-isnull(idItemTaxAmount,0)) * ihExchangeRate) cAmount,                                   
 convert(numeric(18,8),-(idUnitPrice-isnull(idItemTaxAmount,0)) * ihDepExRate) dAmount,            
    
 convert(numeric(18,8),-idActualUnitPrice * reqqty) ActualAmount,--sree            
 convert(numeric(18,8),-idActualUnitPrice * ihExchangeRate *reqqty) cActualAmount,  --sree                      
 convert(numeric(18,8),-idActualUnitPrice * ihDepExRate *reqqty) dActualAmount,     --sree           
 IhCustomerID,    
 convert(numeric(18,8),-(isnull(idItemTaxAmount,0)))GSTAmount    
,convert(numeric(18,8),-(isnull(idItemTaxAmount,0))* ihDepExRate)dGSTAmount,    
 convert(numeric(18,8),-(isnull(idItemTaxAmount,0))* ihExchangeRate)cGSTAmount                                 
from                                   
 losspecialinvoicedetail,losspecialinvoiceheader         
where                                   
 ihInvoiceid = idInvoiceid  and ihshopid = idshopid AND IHCANCELLED = 0 and                                   
 idratetype = 1 and ihproforma = 0 and ihTransFinished = 1                                  
                                   
union all                                  
-- 7                                   
-- (- Qty has to be minus so when multiplying - * - =+ so i am removing the - on values )                                  
--venkitesh 150403                                  
--select                                   
-- grnditemid,            
-- convert(numeric(18,8),( GRNDUnitPrice / GRNDQuantity)  *  grnhExchangeRate) cUnitPrice,               
-- convert(numeric(18,8),( GRNDUnitPrice / GRNDQuantity)  *  grnhDepExRate) dUnitPrice,                                  
-- convert(numeric(18,8),( GRNDUnitPrice / GRNDQuantity) ) UnitPrice,                                  
-- -GRNDQuantity GRNDQuantity, 0 as ratetype,  GrnhGoodsreturnnoteDate , GrnhGoodsreturnnoteID,                                  
-- GrnhGoodsreturnnoteNO, grnhShopid, grncostprice, grncostprice * grnhDepExRate,                                   
-- grncostprice * grnhExchangeRate, 'R' as type,                                   
-- -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                  
-- -- ((GRNDUnitPrice / GRNDQuantity) - grncostprice) margin,                                   
-- -- ((GRNDUnitPrice / GRNDQuantity) - grncostprice) * grnhDepExRate dmargin,                                   
-- -- ((GRNDUnitPrice / GRNDQuantity) - grncostprice) *  grnhExchangeRate cmargin,                                  
-- GRNDUnitPrice-grncostprice*GRNDQuantity margin,                                   
-- (GRNDUnitPrice-grncostprice*GRNDQuantity) * grnhDepExRate dmargin,                 
-- (GRNDUnitPrice-grncostprice*GRNDQuantity) *  grnhExchangeRate cmargin,                                
-- convert(numeric(18,8),-grndUnitPrice) Amount,convert(numeric(18,8),-grndUnitPrice * grnhExchangeRate) cAmount,                                  
-- convert(numeric(18,8),-grndUnitPrice * grnhDepExRate) dAmount                                  
--from                                   
-- losgoodsreturnnoteheader, losgoodsreturnnotedetail                                   
--where                                    
-- GrnhGoodsreturnnoteID  =  GRNDReturnNoteID and                                   
-- grnhShopid =  GRNDShopid AND GrnhCancel = 0             
                                  
--Sreejith Commented Above and rewritten below with joining losinvoicedetail to find the returned items Actual price            
            
select                                   
 grnditemid,            
 convert(numeric(18,8), idActualUnitPrice *  grnhExchangeRate) cActualUnitPrice,  --sree                       
 convert(numeric(18,8), idActualUnitPrice *  grnhDepExRate) dActualUnitPrice,   --sree                
 convert(numeric(18,8), idActualUnitPrice) ActualUnitPrice,  --sree            
    
 --convert(numeric(18,8),( -GRNDUnitPrice / CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END)  *  grnhExchangeRate) cUnitPrice,    --RefNo:1                                
 --convert(numeric(18,8),( -GRNDUnitPrice / CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END)  *  grnhDepExRate) dUnitPrice,        --RefNo:1                           
 --convert(numeric(18,8),( -GRNDUnitPrice / CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END) ) UnitPrice,                           --RefNo:1        
 convert(numeric(18,8),( -GRNDUnitPrice/CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END)-(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))  *  grnhExchangeRate) cUnitPrice,    --RefNo:1                                
 convert(numeric(18,8),( -GRNDUnitPrice/CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END)-(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))  *  grnhDepExRate) dUnitPrice,        --RefNo:1                           
 convert(numeric(18,8),( -GRNDUnitPrice/CASE WHEN GRNDQuantity=0 THEN 1 ELSE GRNDQuantity END)-(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)) ) UnitPrice,                           --RefNo:1        
    
 -GRNDQuantity GRNDQuantity, 0 as ratetype,  GrnhGoodsreturnnoteDate , GrnhGoodsreturnnoteID,                                  
 GrnhGoodsreturnnoteNO, grnhShopid, grncostprice, grncostprice * grnhDepExRate,                                   
 grncostprice * grnhExchangeRate, 'R' as type,                                   
    
 --GRNDUnitPrice-grncostprice*GRNDQuantity margin,                                   
 --(GRNDUnitPrice-grncostprice*GRNDQuantity) * grnhDepExRate dmargin,                                   
 --(GRNDUnitPrice-grncostprice*GRNDQuantity) *  grnhExchangeRate cmargin,                                  
  
-(GRNDUnitPrice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))-grncostprice*GRNDQuantity margin,                                   
-((GRNDUnitPrice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))-grncostprice*GRNDQuantity) * grnhDepExRate dmargin,                                   
-((GRNDUnitPrice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))-grncostprice*GRNDQuantity) *  grnhExchangeRate cmargin,                                  
    
 --convert(numeric(18,8),-grndUnitPrice) Amount,    
 --convert(numeric(18,8),-grndUnitPrice * grnhExchangeRate) cAmount,                                  
 --convert(numeric(18,8),-grndUnitPrice * grnhDepExRate) dAmount,            
 convert(numeric(18,8),-(grndUnitPrice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))) Amount,    
 convert(numeric(18,8),-(grndUnitPrice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)) * grnhExchangeRate) cAmount,                                  
 convert(numeric(18,8),-(grndUnitPrice-isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)) * grnhDepExRate) dAmount,            
     
 convert(numeric(18,8),-idActualUnitPrice * GRNDQuantity) ActualAmount,--sree            
 convert(numeric(18,8),-idActualUnitPrice * grnhExchangeRate *GRNDQuantity) cActualAmount,  --sree                      
 convert(numeric(18,8),-idActualUnitPrice * grnhDepExRate *GRNDQuantity) dActualAmount,     --sree          
 GrnhCustomerID,    
convert(numeric(18,8),-(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0)))GSTAmount    
,convert(numeric(18,8),-(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhdepexrate)dGSTAmount,    
convert(numeric(18,8),-(isnull(losgoodsreturnnotedetail.idItemTaxAmount,0))* grnhexchangerate)cGSTAmount    
                                    
from                                   
 losgoodsreturnnotedetail             
left outer join  losgoodsreturnnoteheader on  GrnhGoodsreturnnoteID  =  GRNDReturnNoteID and                                   
 grnhShopid =  GRNDShopid             
left outer join losinvoicedetail  on idShopID= GRNDShopid  and idInvoiceID=GrnhInvoiceID            
and GRNDItemID=idItemID                                  
where  GrnhCancel = 0             
                                  
UNION ALL                                  
-- 8              
select                                   
 repinvdpartsid,            
 convert(numeric(18,8), repinvdsellrate *  serinvhcmpexrate) cActualUnitPrice,  --sree                       
 convert(numeric(18,8), repinvdsellrate *  seinvhDepExRate) dActualUnitPrice,   --sree                
 convert(numeric(18,8), repinvdsellrate) ActualUnitPrice,  --sree            
     
 --convert(numeric(18,8) , repinvdrate  *  serinvhcmpexrate) cUnitPrice,                                   
 --convert(numeric(18,8) , repinvdrate  *  seinvhDepExRate) dUnitPrice,                             
 --convert(numeric(18,8) , repinvdrate ) UnitPrice,    
 convert(numeric(18,8) , (repinvdrate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty))  *  serinvhcmpexrate) cUnitPrice,                             
 convert(numeric(18,8) , (repinvdrate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty))  *  seinvhDepExRate) dUnitPrice,                             
 convert(numeric(18,8) , (repinvdrate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty))) UnitPrice,    
     
 repinvdqty, 0 as ratetype, serinvhdate ,                                   
 serinvhid , serinvNo , serinvhShopid, repinvdcostprice, repinvdcostprice *  seinvhDepExRate,                                   
 repinvdcostprice * serinvhcmpexrate, 'b',                                   
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                  
 -- (repinvdrate - repinvdcostprice) margin,                                  
 -- (repinvdrate - repinvdcostprice) *  seinvhDepExRate dmargin,                                   
 -- (repinvdrate  - repinvdcostprice) *  serinvhcmpexrate cmargin,                                  
     
 --(repinvdrate - repinvdcostprice*repinvdqty) margin,                                  
 --(repinvdrate - repinvdcostprice*repinvdqty) *  seinvhDepExRate dmargin,                                   
 --(repinvdrate - repinvdcostprice*repinvdqty) *  serinvhcmpexrate cmargin,                                  
 ((repinvdrate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty)) - repinvdcostprice*repinvdqty) margin,                                  
 ((repinvdrate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty)) - repinvdcostprice*repinvdqty) *  seinvhDepExRate dmargin,                                   
 ((repinvdrate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty)) - repinvdcostprice*repinvdqty) *  serinvhcmpexrate cmargin,                                  
     
 --convert(numeric(18,8),RepInvDRate * repinvpackqty) Amount,                                  
 --convert(numeric(18,8),RepInvDRate * ISNULL(serinvhcmpexrate, 1) * repinvpackqty) cAmount,                                  
 --convert(numeric(18,8),RepInvDRate * ISNULL(seinvhDepExRate, 1) * repinvpackqty) dAmount,    
 convert(numeric(18,8),(RepInvDRate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty)) * repinvpackqty) Amount,                                  
 convert(numeric(18,8),(RepInvDRate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty)) * ISNULL(serinvhcmpexrate, 1) * repinvpackqty) cAmount,                                  
 convert(numeric(18,8),(RepInvDRate-(isnull(repinvdItemTaxAmount,0)/repinvpackqty)) * ISNULL(seinvhDepExRate, 1) * repinvpackqty) dAmount,           
            
 convert(numeric(18,8),repinvdsellrate * repinvdqty) ActualAmount,--sree            
 convert(numeric(18,8),repinvdsellrate * serinvhcmpexrate *repinvdqty) cActualAmount,  --sree                      
 convert(numeric(18,8),repinvdsellrate * seinvhDepExRate *repinvdqty) dActualAmount ,    --sree            
serinvhCustomerId,    
 convert(numeric(18,8),(isnull(repinvdItemTaxAmount,0)))GSTAmount    
,convert(numeric(18,8),(isnull(repinvdItemTaxAmount,0))* seinvhDepExRate)dGSTAmount,    
 convert(numeric(18,8),(isnull(repinvdItemTaxAmount,0))* serinvhcmpexrate)cGSTAmount                                 
from                                   
 losinvoicedpartsreplacedetails, losserviceinvheader                                   
where                                   
 serinvhid  =  repinvinvoiceid  and serinvhshopid  =  repinvdshopid AND                                   
 serinvhcancelled = 0                                   
                                  
union all                                  
-- 9                                  
select                                   
 reditemid,             
 convert(numeric(18,8), redActualUnitPrice *  rehExchangeRate) cActualUnitPrice,  --sree                       
 convert(numeric(18,8), redActualUnitPrice *  rehDepExRate) dActualUnitPrice,   --sree                
 convert(numeric(18,8), redActualUnitPrice) ActualUnitPrice,  --sree            
 convert(numeric(18,8),               
 (redUnitPrice / CASE WHEN redquantity=0 THEN 1 ELSE redquantity END) * rehExchangeRate) cUnitPrice,                       --RefNo:1             
 convert(numeric(18,8), (redUnitPrice / CASE WHEN redquantity=0 THEN 1 ELSE redquantity END)  *  rehDepExRate) dUnitPrice, --RefNo:1                      
 convert(numeric(18,8), (redUnitPrice / CASE WHEN redquantity=0 THEN 1 ELSE redquantity END)) posdUnitPrice,               --RefNo:1                     
 redquantity, redRateType, rehExportDate, rehExportID, rehExportNo, rehShopid, redcostprice,                                   
 redcostprice * rehDepExRate, redcostprice * rehExchangeRate, 'S',                                  
 -- To get the margin of sale correctly below part is modified by Regin on 10-11-2009                  
 -- ((redUnitPrice / redquantity) * rehExchangeRate - redcostprice) margin,                                   
 -- ((redUnitPrice / redquantity) - redcostprice) * rehDepExRate  dmargin,                                  
 -- ((redUnitPrice / redquantity) - redcostprice) * rehExchangeRate cmargin,     
 redUnitPrice - redcostprice*redquantity margin,                                   
 (redUnitPrice - redcostprice*redquantity) * rehDepExRate  dmargin,                                  
 (redUnitPrice - redcostprice*redquantity) * rehExchangeRate cmargin,                                  
 convert(numeric(18,8),redUnitPrice) Amount,convert(numeric(18,8),redUnitPrice * rehExchangeRate) cAmount,                                  
 convert(numeric(18,8),redUnitPrice * rehDepExRate) Amount,            
 convert(numeric(18,8),redActualUnitPrice * redquantity) ActualAmount,--sree            
 convert(numeric(18,8),redActualUnitPrice * rehExchangeRate *redquantity) cActualAmount,  --sree                      
 convert(numeric(18,8),redActualUnitPrice * rehDepExRate *redquantity) dActualAmount,     --sree          
rehcustomerid,    
0,0,0                                   
from                                   
 losExportDetail, losExportHeader                                  
where                                   
 rehExportID = redExportID and rehShopID = redShopID AND                                   
 rehCancelled = 0 and rehproforma = 0 and rehtype = 'i'     
   
   
  
  Go

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

/****** Object:  View [dbo].[vwLocalPurchaseInvoiceDetails]    Script Date: 10/11/2012 18:07:00 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vwLocalPurchaseInvoiceDetails]'))
DROP VIEW [dbo].[vwLocalPurchaseInvoiceDetails]
GO

USE [adminv2]
GO

/****** Object:  View [dbo].[vwLocalPurchaseInvoiceDetails]    Script Date: 10/11/2012 18:07:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

  
-- Created By : MANUNADH. U    
-- Created On : 06-09-2012    
-- Purpose    : To create a new report for showing relations of Item, vendor and customer     
--    during a period of time.     
CREATE VIEW [dbo].[vwLocalPurchaseInvoiceDetails] as    
SELECT DISTINCT VW.lphBillDate BillDate,VW.lphVendorID VendorID,V.VendorName,VW.lpditemid Itemid,    
 VW.itemdescription,VW.lphbillid Billid,VW.lphBillNo BillNo,VW.PackQty PurchaseQuantity,  
 (VW.lpdItemUnitPrice+VW.lpdItemTaxAmount)/VW.PackQty PurchaseUnitPrice,PackingTypeName unitname,
 VW.lpdItemTaxAmount BillItemTaxAmount,IH.ihInvoiceDate InvoiceDate,IH.ihinvoiceid Invoiceid,
 IH.ihinvoiceno Invoiceno,ID.idPQuantity SoldQuantity,ID.idUnitPrice/ID.idPQuantity SoldUnitPrice,
 ID.idItemTaxAmount InvItemTaxAmount,IH.ihCustomerID CustomerID,C.CustomerName,VW.lphshopid ShopId
 ,lpidPackingTypeId  
FROM vwlocalpurchasebill VW     
 INNER JOIN LosLocalPurchaseInvoiceDetails LPID ON LPID.lpidBillId=VW.lphbillid AND     
  LPID.lpidShopId=VW.lphshopid AND LPID.lpidItemId=VW.lpditemid    
 INNER JOIN losinvoiceheader IH ON IH.ihinvoiceid=LPID.lpidInvoiceId AND IH.ihShopID=LPID.lpidShopId    
 INNER JOIN LOsInvoiceDetail ID ON ID.idInvoiceID=IH.ihInvoiceID AND ID.idShopID=IH.ihShopID    
  AND LPID.lpidItemId=ID.iditemid    
 INNER JOIN aVendorMaster V ON V.VendorID=VW.lphVendorID    
 INNER JOIN aCustomerMaster C ON C.CustomerID=IH.ihCustomerID    
 left outer join aPackingType pt on LPID.lpidPackingTypeId=pt.PackingTypeID   

WHERE VW.lphCancelled=0 AND IH.ihCancelled=0 --AND VW.lphshopid=2 AND lpditemid=1838    
    
GO

Go

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

--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--FINDSP
--STORED PROCEDURE CREATIONS AND ALTERATIONS

--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
--**********************************************************************************************************************
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_319
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO
/****** Object:  StoredProcedure [dbo].[spCustomerSettlement]    Script Date: 05/28/2011 14:13:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCustomerSettlement]') AND type in (N'P', N'PC'))
BEGIN
	DROP PROCEDURE spCustomerSettlement
END
GO                   
/*                              
-------------------------------------------------------------------------------------------                                      
SPName      : spCustomerSettlement                                        
Coded By    : Vinoth Murugan                                        
Date        : 16-02-2010                                        
Purpose     : To speed up Customer settlement.                             
Modified on : 17/03/2007                            
Modified By : VINOTHMURUGAN V                                       
-------------------------------------------------------------------------------------------                                
Modified On : 20-04-2010          
Modified By : Sreejith G A          
Purpose: Added the condition of fhinvoicecancelled = 0       
     and fhshopid=0 in Fine portion to populate Fine Invoices generated from Acc Invoices.      
-------------------------------------------------------------------------------------------         
Modified On : 22-12-2010          
Modified By : Shine Das  
Purpose: DELETE FROM #tempid changed to TRUNCATE TABLE #tempid  
-------------------------------------------------------------------------------------------                                 
Modified On : 19-06-2012          
Modified By : Jyothish 
Purpose:  TaxAmount is Added to serviceinvoice
   
*/                                   
create PROC spCustomerSettlement(@customerid AS INT,@departmentid AS INT,@companyid AS INT)                                               
AS                                         
DECLARE @ID  INT,@INDEX  INT,@RECCOUNT  INT,@AMT  NUMERIC(18,2),@AMT1  NUMERIC(18,2),                                            
   @dblamt NUMERIC(18,2),@billdate datetime,@billno int,                                            
   @billamt NUMERIC(18,2),@Discount NUMERIC(18,2),@shopid int ,@INVAMT NUMERIC(18,2),@product int  ,@TaxAmount NUMERIC(18,2)                                  
                                             
BEGIN                                             
                                        
CREATE TABLE #temp (Location varchar(50),InvoiceNo varchar(50),InvoiceDate  datetime,                                              
InvoiceAmount numeric(18,2),SettleAmount numeric(18,2),InvoiceID int,InvoiceType  varchar(20),                                              
ShopID int)                                    
                                    
create table #tempid(id int identity(1,1),InvoiceID int,Product int,discount NUMERIC(18,2),taxamount NUMERIC(18,2))    
                     
                      
                      
                      
----------------------------------------------------------------                      
-------------------------------------------------------------------------------                            
--Client      : SIMDI                            
--Modified on : 17/03/2010                            
--Modified By : VINOTHMURUGAN V                            
--Purpose     : Adding Fine Amount.                            
TRUNCATE TABLE  #tempid                                  
If @departmentid = 0                                     
BEGIN                                  
 INSERT INTO #TEMPID                                  
 select fhfineid, 0,'0.00','0.00' from aFineHeader                                   
 where fhcompanyid = @companyid and fhcustomerid = @customerid  and fhinvoicecancelled=0 and fhshopid=0                               
                                             
END                                  
     Else                                    
BEGIN                                  
  INSERT INTO #TEMPID                                  
     select fhfineid, 0,'0.00','0.00' from aFineHeader                                    
     where fhcompanyid = @companyid and fhcustomerid = @customerid                                  
     and fhDepartmentID = @departmentid   and fhinvoicecancelled=0 and fhshopid=0                                   
End                                   
                                   
SET @INDEX = 1                                             
SET @RECCOUNT =(SELECT COUNT(id) from #TEMPid)                             
                                              
WHILE (@INDEX <= @RECCOUNT)                                    
BEGIN                                     
                           
 SET @ID = (SELECT InvoiceID FROM #TEMPID WHERE ID= @INDEX)                                
                          
                            
 set @INVAMT =(select isnull(sum(fdfineAmount*fhRespExchangeRate),0) amount from afinedetail inner join afineheader on fdfineid=fhfineid                                     
 where   fdfineid = @ID )                             
                             
-- SET @INVAMT =(Select (@INVAMT * fhrespexchangerate) from  afineheader                             
-- where  fhcompanyid = @companyid and fhfineid = @ID)                        
                      
 set @amt=(select isnull(sum(AmountReceived),0) as amt from receiptvoucherdetails rd,                                     
 receiptvoucherheader rh where rd.companyid = rh.companyid and rh.companyid = @companyid                                    
 and rd.receiptid = rh.receiptid and rh.cancelled = 0 and rd.fineid = @ID)                           
                               
                                   
 SET @AMT1 =( SELECT isnull(sum(settlementamount),0) FROM customersettlementdetail cd, customersettlementheader ch                                   
 WHERE  ch.companyid = cd.companyid and ch.csid = cd.csid and ch.cancelled = 0                                    
 and ch.companyid = @companyid  AND cd.fineid = @ID)                          
                          
                      
--select *  FROM customersettlementdetail cd, customersettlementheader ch                            
-- WHERE  ch.companyid = cd.companyid and ch.csid = cd.csid and ch.csid=18691                      
--                                
--                                    
 INSERT INTO #TEMP                                  
 SELECT 'Head Quarters',fhfineno,fhinvoicedate,ISNULL( (@INVAMT-(@AMT1+@amt)),0),'0.00',                                  
 fhfineid,'FINE',0  from aFineHeader                                    
 where fhcompanyid = @companyid and fhcustomerid = @customerid                                  
 and fhDepartmentID = @departmentid  AND fhfineid =@ID                                
                                    
set @index = @index + 1                                   
 END                            
                         
-------------------------------------------------------------------------------                        
--------------------------------------------------------------                                    
                                    
IF @departmentid = 0                                      
begin                                    
   insert into #tempid                                    
   select InvoiceID,Product,isnull(discount,0)discount ,ISNULL(TaxAmount,0) taxamount                                   
   from accountsinvoiceheader                                     
   where Cancelled=0 and proforma = 0 and cashinvoice = 0 and companyid = @companyid                                    
   and customerid = @customerid                                    
end                                    
   Else                                    
begin                                    
   insert into #tempid                                    
   select InvoiceID,Product,isnull(discount,0)discount ,ISNULL(TaxAmount,0) taxamount                                    
   from accountsinvoiceheader                                     
   where Cancelled=0 and proforma = 0 and cashinvoice = 0 and companyid = @companyid                                    
   and customerid = @customerid and DepartmentID= @departmentid                                    
           
                                    
End                                    
                                     
SET @INDEX = 1                                
SET @RECCOUNT =(SELECT COUNT(id) from #TEMPid)                                     
                                              
WHILE (@INDEX <= @RECCOUNT)                                    
BEGIN                                       
                                    
 SET @ID = (SELECT InvoiceID FROM #TEMPID WHERE ID= @INDEX)                                    
 set @product =(SELECT Product FROM #TEMPID WHERE ID= @INDEX)                                    
 set @discount = (SELECT discount FROM #TEMPID WHERE ID= @INDEX)  
 set @TaxAmount = (SELECT TaxAmount FROM #TEMPID WHERE ID= @INDEX)  
                                
                                      
 set @INVAMT =(select isnull(sum(ServiceQty * Amount),0) prodamount from ServiceInvoiceDetails                                     
 where companyid = @companyid and @product=0 and invoiceid = @ID )                                     
                                
 set @INVAMT = (@INVAMT+@TaxAmount) - @discount                                    
                                             
 set @amt=(select isnull(sum(settlementamount),0) as amt from customersettlementdetail cd,                                     
 customersettlementheader ch where cd.companyid = @companyid and                                     
 cd.csid = ch.csid and cd.companyid = ch.companyid and cancelled = 0 and AccInvoiceID = @ID)                                    
                                             
 set @amt1=(select isnull(sum(AmountReceived),0) as amt1 from receiptvoucherdetails rd,                                     
 receiptvoucherheader rh where rd.companyid = rh.companyid and rh.companyid = @companyid                                    
 and rd.receiptid = rh.receiptid and rh.cancelled = 0 and rd.hqAccountsInvoiceID = @ID)                                   
                                
 insert into #temp                                    
 select 'Head Quarters',InvoiceNo,InvoiceDate,@INVAMT - ((@amt+@amt1 + isnull(h.discount,0))),'0.00',h.InvoiceID,                                    
 'HSERVICE',0 from accountsinvoiceheader h                                      
 where companyid = @companyid and Cancelled=0 and proforma = 0 and cashinvoice = 0                                     
 and customerid = @customerid  and (@amt+@amt1)< @INVAMT and h.invoiceid = @ID                                   
                                
 set @index = @index + 1                                    
                                               
end                                    
                                    
                                    
 ----------------------------------------------------------------                                      
TRUNCATE TABLE #tempid                                  
If @departmentid = 0                      
begin                                    
 insert into #tempid                                     
 select dcniD, 0,'0.00','0.00' from debitcreditnote                                   
 where DCNCancelled=0 and dcndebit = 1 and dcncompanyid = @companyid                                    
 and dcncustomerid = @customerid                                  
end                                  
    Else                            
begin                                  
 insert into #tempid                                    
 select dcniD, 0,'0.00','0.00' from debitcreditnote                                    
 where DCNCancelled=0 and dcndebit = 1 and dcncompanyid = @companyid                                  
 and dcndepartmentid =@departmentid                                   
 and dcncustomerid = @customerid              end                                  
                                  
SET @INDEX = 1                                             
SET @RECCOUNT =(SELECT COUNT(id) from #TEMPid)                                              
          
WHILE (@INDEX <= @RECCOUNT)                                    
BEGIN                                       
                                    
 SET @ID = (SELECT InvoiceID FROM #TEMPID WHERE ID= @INDEX)                                    
                                   
 SET @AMT = (SELECT isnull(sum(settlementamount),0) FROM customersettlementdetail cd,                                   
 customersettlementheader ch WHERE  ch.companyid = cd.companyid and                                   
 ch.csid = cd.csid and ch.cancelled = 0 and ch.companyid = @companyid AND cd.dcnid = @ID)                                   
                                
 SET @AMT1 =(SELECT isnull(sum(AmountReceived),0) FROM receiptvoucherdetails rd,                                   
 receiptvoucherheader rh WHERE rd.companyid = rh.companyid and rh.companyid = @companyid                                   
 and rd.receiptid = rh.receiptid and rh.cancelled = 0 and rd.dcnid = @ID )                                  
                                
                                
 INSERT INTO #TEMP                                  
 SELECT 'Head Quarters',dcnno,dcnDate,ISNULL((dcnAmount-(@AMT + @AMT1)),0),'0.00',dcnid,'HDEBIT',0                                  
 from debitcreditnote where DCNCancelled=0 and dcndebit = 1 and dcncompanyid = @companyid                                  
 and dcndepartmentid =@departmentid  and dcncustomerid = @customerid AND (@AMT + @AMT1) <= dcnAmount                                  
 AND dcniD = @ID                                  
                                
 set @index = @index + 1                                   
END                  
                                  
                                  
-----------------------------------------------------------------                                   
TRUNCATE TABLE  #tempid                                  
If @departmentid = 0                                     
BEGIN                                  
 INSERT INTO #TEMPID                                  
 select phpaymentID, 0,'0.00','0.00' from ahqpaymentvoucherheader                                   
 where phcancelled =0 and phcompanyid = @companyid and phcustomerid = @customerid                                    
                                             
END                                  
     Else                                    
BEGIN                                  
  INSERT INTO #TEMPID                                  
     select phpaymentID, 0,'0.00','0.00' from ahqpaymentvoucherheader                                    
     where phcancelled =0 and phcompanyid = @companyid and phcustomerid = @customerid                                  
     and phDepartmentID = @departmentid                                  
End                                   
                                   
SET @INDEX = 1                                             
SET @RECCOUNT =(SELECT COUNT(id) from #TEMPid)                  
                                              
WHILE (@INDEX <= @RECCOUNT)                                    
BEGIN                                     
                                   
 SET @ID = (SELECT InvoiceID FROM #TEMPID WHERE ID= @INDEX)                                   
                                      
 SET @AMT =(SELECT isnull(sum(AmountReceived),0) FROM receiptvoucherdetails rd, receiptvoucherheader rh                                  
 WHERE  rd.companyid = rh.companyid and rh.companyid = @companyid                                   
 and rd.receiptid = rh.receiptid and rh.cancelled = 0 and rd.phpaymentid = @ID)                                  
                                   
 SET @AMT1 =( SELECT isnull(sum(settlementamount),0) FROM customersettlementdetail cd, customersettlementheader ch                                   
 WHERE  ch.companyid = cd.companyid and ch.csid = cd.csid and ch.cancelled = 0                                    
 and ch.companyid = @companyid  AND cd.paymentid = @ID)                   
                                    
 INSERT INTO #TEMP                                  
 SELECT 'Head Quarters',phpaymentno,phPaymentDate,ISNULL( phcustomeramount- (@AMT+@AMT1),0),'0.00',                                  
 phpaymentid,'payment',0  from ahqpaymentvoucherheader                                    
 where phcancelled =0 and phcompanyid = @companyid and phcustomerid = @customerid                                  
 and phDepartmentID = @departmentid AND (@AMT+@AMT1)<= phcustomeramount  AND phpaymentID =@ID                                  
                                    
 set @index = @index + 1                                   
 END                                  
                                
insert into #temp                                           
exec SPPopulateShopInvoiceDetails_vw @customerid ,@companyid ,@departmentid                               
                                
select * from #temp where InvoiceAmount > 0                                  
Drop table #temp                                    
Drop table #tempid                                    
end    


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:M_318
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDishCategorySales]') AND type in (N'P', N'PC'))
BEGIN
	DROP PROCEDURE spDishCategorySales
END
GO  
-- =============================================          
-- Author:  <AADYAKUMAR.D.V>          
-- Create date: <17/01/2012>          
-- =============================================          
-- Modified by : AADYAKUMAR.D.V              
-- Date        : 19/01/2012                  
-- RefNo       : 1                 
-- Comments    : Bug fixed existing qry              
--==============================================      
 --- Modified by : Jyothish.SR        
-- Date        : 16/06/2012                  
-- RefNo       : 2                 
-- Comments    : Bug fixed  Qquatiy problem              
--==============================================      

create PROCEDURE spDishCategorySales              
@FromDate AS varchar(10),          
@ToDate AS varchar(10),          
@strDishCategoryid as varchar(2000)            
AS                
BEGIN                  
 declare @strSql as nvarchar(3000)          
 if @strDishCategoryid=''          
 begin          
 -- RefNo:1----------------------------------------start---------------------------------------------------------           
  -- set @strsql='                
  --SELECT distinct fb_pd_processid,fb_dd_dishcode ItemCode,fb_dd_dishname DishName,''Dish'',fb_pd_reusedqty Qty,                
  --fb_pd_Rate SP,fb_pd_cost CP,fb_pd_Rate-fb_pd_cost Margin,((fb_pd_Rate-fb_pd_cost)/ fb_pd_Rate)* 100 MarginPer,          
  --subgroup.Fb_Ds_DishSubGroupName                 
  --FROM Losposfandbheader INNER JOIN fb_processdetail                 
  --ON fb_pd_processid=poshbillid AND fb_pd_AddedItemtype=0 AND                 
  --fb_pd_outletid=poshShopID AND poshCompanyID=fb_pd_companyid                
  --INNER JOIN TILLHISTORY ON poshTillHistID=till_hist_id INNER JOIN                 
  --fb_dishdetails dishdetails ON fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid          
  --inner join FB_Dishsubgroup subgroup on subgroup.Fb_Ds_DishSubGroupID = dishdetails.fb_dd_dishsubgroupid          
  --and subgroup.Fb_Ds_CompanyID = dishdetails.fb_dd_companyid                 
  --where CAST(LEFT(poshBillDate,11) AS DATETIME)>='''+ @FromDate + ''' AND CAST(LEFT(poshBillDate,11) AS DATETIME)<=''' + @ToDate + '''           
  --'      -- RefNo -2  sum(fb_pd_reusedqty) added    
   set @strsql='                
  SELECT distinct fb_pd_processid,fb_dd_dishcode ItemCode,fb_dd_dishname DishName,''Dish'', sum(fb_pd_reusedqty) Qty,                
  sum(fb_pd_Rate*fb_pd_reusedqty) SP,fb_pd_cost CP,fb_pd_Rate-fb_pd_cost Margin,  
  ((fb_pd_Rate-fb_pd_cost)/ fb_pd_cost)* 100 MarginPer,          
  subgroup.Fb_Ds_DishSubGroupName ,fb_pd_dishid,poshBillNo                
  FROM Losposfandbheader INNER JOIN fb_processdetail                 
  ON fb_pd_processid=poshbillid AND fb_pd_AddedItemtype=0 AND                 
  fb_pd_outletid=poshShopID AND poshCompanyID=fb_pd_companyid                
  INNER JOIN                 
  fb_dishdetails dishdetails ON fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid          
  inner join FB_Dishsubgroup subgroup on subgroup.Fb_Ds_DishSubGroupID = dishdetails.fb_dd_dishsubgroupid          
  and subgroup.Fb_Ds_CompanyID = dishdetails.fb_dd_companyid                  
  where CAST(LEFT(poshBillDate,11) AS DATETIME)>='''+ @FromDate + ''' AND CAST(LEFT(poshBillDate,11) AS DATETIME)<=''' + @ToDate + '''           
  and  poshCancelled=0        
   group by poshBillNo,fb_pd_processid,fb_dd_dishcode  ,fb_dd_dishname,fb_pd_cost ,fb_pd_Rate,Fb_Ds_DishSubGroupName,fb_pd_dishid        
  '          
-- RefNo:1----------------------------------------end---------------------------------------------------------        
execute sp_executesql @strsql            
end          
 else IF @FromDate<>0 AND @ToDate<>0                
 BEGIN          
 --RefNo -2  sum(fb_pd_reusedqty) added      
 -- RefNo:1----------------------------------------start---------------------------------------------------------            
  --set @strsql='                
  --SELECT distinct fb_pd_processid,fb_dd_dishcode ItemCode,fb_dd_dishname DishName,''Dish'',fb_pd_reusedqty Qty,                
  --fb_pd_Rate SP,fb_pd_cost CP,fb_pd_Rate-fb_pd_cost Margin,((fb_pd_Rate-fb_pd_cost)/ fb_pd_Rate)* 100 MarginPer,          
  --subgroup.Fb_Ds_DishSubGroupName                 
  --FROM Losposfandbheader INNER JOIN fb_processdetail                
  --ON fb_pd_processid=poshbillid AND fb_pd_AddedItemtype=0 AND                 
  --fb_pd_outletid=poshShopID AND poshCompanyID=fb_pd_companyid                
  --INNER JOIN TILLHISTORY ON poshTillHistID=till_hist_id INNER JOIN                
  --fb_dishdetails dishdetails ON fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid          
  --inner join FB_Dishsubgroup subgroup on subgroup.Fb_Ds_DishSubGroupID = dishdetails.fb_dd_dishsubgroupid          
  --and subgroup.Fb_Ds_CompanyID = dishdetails.fb_dd_companyid                 
  --where CAST(LEFT(poshBillDate,11) AS DATETIME)>='''+ @FromDate + ''' AND CAST(LEFT(poshBillDate,11) AS DATETIME)<=''' + @ToDate + '''           
  --and subgroup.Fb_Ds_DishSubGroupID in (' + @strDishCategoryid + ')'          
  set @strsql='                
  SELECT distinct fb_pd_processid,fb_dd_dishcode ItemCode,fb_dd_dishname DishName,''Dish'',sum(fb_pd_reusedqty) Qty,                
  sum(fb_pd_Rate*fb_pd_reusedqty) SP,fb_pd_cost CP,fb_pd_Rate-fb_pd_cost Margin,  
  ((fb_pd_Rate-fb_pd_cost)/ fb_pd_cost)* 100 MarginPer,          
  subgroup.Fb_Ds_DishSubGroupName ,fb_pd_dishid,poshBillNo                
  FROM Losposfandbheader INNER JOIN fb_processdetail                 
  ON fb_pd_processid=poshbillid AND fb_pd_AddedItemtype=0 AND                 
  fb_pd_outletid=poshShopID AND poshCompanyID=fb_pd_companyid                
  INNER JOIN                 
  fb_dishdetails dishdetails ON fb_dd_dishid=fb_pd_dishid AND fb_dd_companyid=fb_pd_companyid          
  inner join FB_Dishsubgroup subgroup on subgroup.Fb_Ds_DishSubGroupID = dishdetails.fb_dd_dishsubgroupid          
  and subgroup.Fb_Ds_CompanyID = dishdetails.fb_dd_companyid                 
  where CAST(LEFT(poshBillDate,11) AS DATETIME)>='''+ @FromDate + ''' AND CAST(LEFT(poshBillDate,11) AS DATETIME)<=''' + @ToDate + '''           
  and subgroup.Fb_Ds_DishSubGroupID in (' + @strDishCategoryid + ') and  poshCancelled=0        
  group by poshBillNo,fb_pd_processid,fb_dd_dishcode  ,fb_dd_dishname,fb_pd_cost ,fb_pd_Rate,Fb_Ds_DishSubGroupName,fb_pd_dishid        
'          
-- RefNo:1----------------------------------------end---------------------------------------------------------        
execute sp_executesql @strsql            
 END                
END       
        

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Added missing stored procedures related to Expiry Email alert on 07.08.12
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO
/****** Object:  StoredProcedure [dbo].[splocalpurchasecosting]    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].[splocalpurchasecosting]') AND type in (N'P', N'PC'))
drop proc [dbo].[splocalpurchasecosting]
go
--exec splocalpurchasecosting 47 ,2,35                
                
              
---------------------------------------------------------------------------                  
--Create By : VinothMurugan V.                  
--Date     : 26/07/2010                  
--Purpose   : Doing Direct Local Purchase Costing From Local Purchase Bill                  
--ReQuest By: Kooddoo                  
---modified by : Jyothish S R                
--Date      :09/08/2010                
----purpose division by zero erro                
---------------------------------------------------------------------------        
--Ref.No.1            
--Modified By :AADYA KUMAR D V        
--Modified on :24/11/2011        
--Modification:Just remove hardcoded department id        
---------------------------------------------------------------------------                 
--Ref.No.2            
--Modified By :AADYA KUMAR D V        
--Modified on :26/06/2012        
--Modification:Adding exchange rate to correct the costing value,    
--            :if purchase is not in inventory currency          
---------------------------------------------------------------------------    
--Ref.No.3          
--Modified By :AADYA KUMAR D V        
--Modified on :28/06/2012        
--Modification:Increase field width of numeric decimals to fix rounnding problem          
---------------------------------------------------------------------------     
--Ref.No.4          
--Modified By :AADYA KUMAR D V        
--Modified on :28/06/2012        
--Modification:When doing costing in Auto and P&C ,both values showing a difference in decimal part           
---------------------------------------------------------------------------               
--select * from aitem where itemid = 2294                   
--exec splocalpurchasecosting 1,3,1002    
                    
CREATE procedure [dbo].[splocalpurchasecosting] (@departmentid int,@Shopid int,@Billid int)                      
as                      
begin                      
declare @strPrefix  as varchar(50)                      
Declare @maxNo as varchar(50)                      
         
 --set @strPrefix =(SELECT Prefix FROM aPrefix WHERE departmentID=28  AND FinancialId = (Select FinancialId from aFinancialYear where CurFinancialYear = 1) --Ref.No.1                           
 set @strPrefix =(SELECT Prefix FROM aPrefix WHERE departmentID=@departmentid  AND FinancialId = (Select FinancialId from aFinancialYear where CurFinancialYear = 1) --Ref.No.1                     
     and InterfaceID = 2011 and ShopId is null and ShopId is null)                      
                      
 If (select count(@strPrefix) ) =0                      
  begin                       
   set @strPrefix = null                      
  End                       
                                              
If @departmentid = 0                       
  begin                       
   set @maxNo =(Select isnull(max(convert(int,right(lpchcostingno,len(lpchcostingno)- Len(@strPrefix)))),0)                       
   from loaLocalPurchaseCostingHeader where len(lpchcostingno)>len(@strPrefix) and                       
   isnumeric(isnull(right(lpchcostingno,len(lpchcostingno)- Len(@strPrefix) ),0)) =1                       
   and substring(lpchcostingno,1,len(@strPrefix))=@strPrefix)                      
  end                      
Else                      
  begin                      
   set @maxNo = (Select isnull(max(convert(int,right(lpchcostingno,len(lpchcostingno)- Len(@strPrefix) ))),0)                      
   from loaLocalPurchaseCostingHeader where  lpchDepartmentid= @departmentid and len(lpchcostingno)>len(@strPrefix)                       
   and isnumeric(isnull(right(lpchcostingno,len(lpchcostingno)- Len(@strPrefix)),0)) = 1                       
   and substring(lpchcostingno,1,len(@strPrefix))= @strPrefix)                      
  End                       
                         
If isnull(@maxNo,0) = 0                            
   begin                      
    set @maxNo = '1'                      
    end                      
else                      
   begin                      
     set @maxNo = (select @maxNo + 1)                      
   End                       
   --select  (@strPrefix + @maxNo)                      
                  
                    
insert into loaLocalPurchaseCostingHeader                    
select (select isnull(max(lpchcostingid),0)+1 from loaLocalPurchaseCostingHeader),(select  (@strPrefix + @maxNo)),lphbilldate,lphbillid,lphshopid,Null,lphremarks,1,                    
'fies',(select inventoryid from aPackageSettings),(select GoodsInTransitID from aPackageSettings),lphdepartmentid,lphcompanyid,0,0,NUll,'fies',Null,                    
(select getdate()),Null,(select CURRENT_TIMESTAMP) from LosLocalPurchaseHeader where lphshopid = @Shopid and lphbillid = @Billid                    
                    
create table #temp(lpcdcostingid int,lpcddetailid int identity(1,1),                  
lpcditemid int,                  
lpcdcostedprice numeric(28,16),                    
lpcditemqty numeric(18,8),   --Ref.No.3                  
lpcdbillunitprice numeric(28,16),                  
lpcdolditemcostprice numeric(18,8), --Ref.No.3                    
lpcdnewitemcostprice numeric(28,16)                  
)                    
              
insert into #temp                    
select (select isnull(max(lpchcostingid),1) from loaLocalPurchaseCostingHeader),lpditemid,(lpditemunitprice/lpditemquantity),                  
lpditemquantity,lpditemunitprice/lpditemquantity,(select itemrate from aitem where itemid=lpditemid),'0.00'                  
from losLocalPurchaseDetail where lpdshopid = @Shopid and lpdbillid = @Billid                  
                  
--------------------------                  
declare @totalStock as numeric(18,8) --Ref.No.3                    
declare @costingid as int            
declare @index as int                  
declare @count as int                   
declare @lpditemid as int                    
--declare @olditemrate as int --Ref.No.4   
declare @olditemrate as numeric(18,8) --Ref.No.4     
    
--Ref.No.2---start---      
declare @exchangerate as numeric(18,8)  --Ref.No.3     
declare @lpcdnewitemcostprice as numeric(18,8)  --Ref.No.3     
declare @DirectLocalPurchaseCosting as bit    
--Ref.No.2----end----     
                  
set @costingid = (select isnull(max(lpchcostingid),1) from loaLocalPurchaseCostingHeader)                  
set @count = (select count(lpcddetailid) from #temp where lpcdcostingid = @costingid )                  
set @index = 1      
    
--Ref.No.2---start---        
set @DirectLocalPurchaseCosting=(select DirectLocalPurchaseCosting from LOsSettings where ShopId=@Shopid)     
if @DirectLocalPurchaseCosting=1    
begin               
set @exchangerate= (select lphexchangerate from LosLocalPurchaseHeader where lphshopid = @Shopid and lphbillid = @Billid)                 
end    
else    
begin    
set @exchangerate= 1    
end    
--Ref.No.2----end----    
               
while(@index <= @count)                  
begin                  
 set @lpditemid = (select lpcditemid from #temp where lpcdcostingid = @costingid and lpcddetailid = @index )                  
                  
 set @totalStock = (select isnull(sum(gsstock),0) from vwinquirygodownstock where  gsitemid = @lpditemid ) +                   
       (select isnull(sum(stock),0) from vwinquiryshopstock  where itemid = @lpditemid) -                  
       (select isnull(sum(lpdItemQuantity),0) from loslocalpurchaseheader h, loslocalpurchasedetail d where                   
       h.lphbillid=d.lpdbillid and h.lphShopId=d.lpdShopId and h.lphcosted=0 and d.lpditemid=@lpditemid and lphcancelled=0)                  
                  
 set @olditemrate = (select itemrate from aitem where itemid=@lpditemid)                  
 ----(((dbltotstock * dblolditemrate) + _                  
 ----                (!lpcditemqty * !lpcdcostedprice)) / (dbltotstock + !lpcditemqty))    
          
if @totalStock > 0               
 begin     
 --Ref.No.2---start---     
 --update  #temp set lpcdnewitemcostprice =( ((@totalStock * @olditemrate) + (lpcdcostedprice * lpcditemqty))/(@totalStock + lpcditemqty ) )                   
 --where lpcdcostingid = @costingid and  lpcddetailid = @index   and  @totalStock + lpcditemqty <>0      
 --set @lpcdnewitemcostprice=(select lpcdnewitemcostprice from #temp  where lpcdcostingid = @costingid and  lpcddetailid = @index   and  @totalStock + lpcditemqty <>0 )                   
 update  #temp set lpcdnewitemcostprice =( ((@totalStock * @olditemrate) + (lpcdcostedprice * lpcditemqty*@exchangerate))/(@totalStock + lpcditemqty ) )                   
 where lpcdcostingid = @costingid and  lpcddetailid = @index   and  @totalStock + lpcditemqty <>0      
 --set @lpcdnewitemcostprice=(select lpcdnewitemcostprice from #temp  where lpcdcostingid = @costingid and  lpcddetailid = @index   and  @totalStock + lpcditemqty <>0 )            
 --Ref.No.2----end----    
 End              
Else              
 begin     
  --Ref.No.2---start---             
 --update  #temp set lpcdnewitemcostprice=(lpcdcostedprice) where  lpcdcostingid = @costingid and  lpcddetailid = @index               
 update  #temp set lpcdnewitemcostprice=(lpcdcostedprice*@exchangerate) where  lpcdcostingid = @costingid and  lpcddetailid = @index               
 --Ref.No.2----end----    
End     
    
 --Ref.No.2---start---     
if @DirectLocalPurchaseCosting=1    
begin    
update  #temp set lpcdcostedprice=(lpcdcostedprice*@exchangerate) where  lpcdcostingid = @costingid and  lpcddetailid = @index               
update  #temp set lpcdbillunitprice=(lpcdbillunitprice*@exchangerate) where  lpcdcostingid = @costingid and  lpcddetailid = @index               
end    
 --Ref.No.2----end----    
            
--- @totalStock + lpcditemqty <>0 added for avoid divsion by zeoro error                 
    update aitem set itemrate= lpcdnewitemcostprice from #temp where itemid=lpcditemid and lpcddetailid = @index and lpcdcostingid = @costingid                  
 if @olditemrate <> (select lpcdnewitemcostprice from #temp where  lpcdcostingid = @costingid and  lpcddetailid = @index )                  
 begin                   
  Update losshopitemshipmentdetail set pricechanged=1 from #temp where itemid=lpcditemid                  
 end                  
                  
 set @index = @index +1                  
end                  
                  
insert into loalocalpurchasecostingdetail                  
select * from #temp                  
                  
drop table #temp                  
                  
end 
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spSaveExpiryEmailSettings]') AND type in (N'P', N'PC'))
BEGIN
	DROP PROCEDURE spSaveExpiryEmailSettings
END
GO  
 /*     
-----------------------------------------------------------------------------------------------------------------------------------  
 --Created on   :  10/09/2009         
 --Created by   :  MANUNADH.U              
 --Description  :            
 --Usage		  :  [dbo].[spSaveExpiryEmailSettings] 'admindsnv2','adminv2','fiesadmin','fiesadmin003','mail.fi-es.com',26,'manu','manunadh.u@fi-es.com','manunadhu',5     
------------------------------------------------------------------------------------------------------------------------------------    
      
*/  
  
CREATE PROCEDURE [dbo].[spSaveExpiryEmailSettings] 

@SMTPhost varchar(50) = '',
@Port int = 0,
@DisplayName varchar(50) = '',
@UserName varchar(50) = '',
@EmailID varchar(50) = '',
@Password varchar(50) = '',
@GracePeriod int = 0

AS  
  
BEGIN  
	SET NOCOUNT ON     
		
		DELETE From [dbo].ExpiryEmailSettings

		INSERT INTO [dbo].ExpiryEmailSettings
		(			
			[SMTPhost],
			[Port],
			[DisplayName],
			[UserName],
			[EmailID],
			[Password],
			[GracePeriod]
		)
		VALUES
		(			
			@SMTPhost,
			@Port,
			@DisplayName,
			@UserName,
			@EmailID,
			@Password,
			@GracePeriod
		)	
		   
	SET NOCOUNT OFF    
END
-------------------------------------------------------------------------------------------------------------
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetExpiryEmailSettings]') AND type in (N'P', N'PC'))
BEGIN
	DROP PROCEDURE spGetExpiryEmailSettings
END
GO
/*      
-----------------------------------------------------------------------------------------------------------------------------------  
 Created on   :  10/09/2009          
 Created by   :  MANUNADH.U              
 Description  :          
 Usage		  :  [dbo].[spGetExpiryEmailSettings]      
------------------------------------------------------------------------------------------------------------------------------------    
      
*/  
GO
  
CREATE PROCEDURE [dbo].[spGetExpiryEmailSettings]   

AS  
  
BEGIN  
	SET NOCOUNT ON     
   
		SELECT   
			SMTPhost,
			Port,
			DisplayName,
			UserName,
			EmailID,
			Password,
			GracePeriod
	   
		FROM [dbo].ExpiryEmailSettings
		   
	SET NOCOUNT OFF    
END
------------------------------------------------------------------------------------------------------------------
GO
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spGetExpiryEmailCompanySettings]') AND type in (N'P', N'PC'))
BEGIN
	DROP PROCEDURE spGetExpiryEmailCompanySettings
END
GO     
/*
-----------------------------------------------------------------------------------------------------------------------------------  
 Created on   :  10/09/2009             
 Created by   :  MANUNADH.U              
 Description  :          
 Usage		  :  [dbo].[spGetExpiryEmailCompanySettings] 'Albatross'   
------------------------------------------------------------------------------------------------------------------------------------    
*/  
GO
  
create PROCEDURE [dbo].[spGetExpiryEmailCompanySettings]

	@ProductName varchar(100) = ''
	--,@CompanyID int = 0 

AS  
  
BEGIN  
	SET NOCOUNT ON     
			
		IF(@ProductName='Magnolia')
		BEGIN
			SELECT 
				CM.[Name],  
				CM.[Address1],
				CM.[Address2],
				CM.[Address3],
				GETDATE()AS 'ServerDate',
				--PS.[PAckageDate],
				PS.[instdate],
				PS.[lockdate],
				PS.[tempchar]
		   
			FROM [dbo].aPAckageSettings PS
				INNER JOIN [dbo].aCompanyMaster CM ON CM.CompanyID=PS.companyid
			--WHERE PS.companyid=@CompanyID
		END	
		
		IF(@ProductName='Albatross')
		BEGIN
			SELECT
				CM.[Name],  
				CM.[Address1],
				CM.[Address2],
				CM.[Address3],
				GETDATE()AS 'ServerDate',
				SL.[instdate],
				SL.[lockdate],
				SL.[extensionno],
				SL.[tempchar]
			FROM [dbo].settinglog SL
				INNER JOIN [dbo].CompanyMaster CM ON CM.CompanyID=SL.companyId
			--WHERE SL.companyId=@CompanyID
		END
		
		IF(@ProductName='Hrms')
		BEGIN
			
			SELECT top 1
				CM.[Name],  
				CM.[Address1],
				CM.[Address2],
				CM.[Address3],
				GETDATE()AS 'ServerDate',
				SL.[instdate],
				SL.[lockdate],
				SL.[extensionno],
				SL.[tempchar]
			FROM [dbo].settinglog SL,[dbo].pCompanyMaster CM 
		END
	SET NOCOUNT OFF    
END
GO
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID: Missing Stored procedures found in SIMDI 07.08.12
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
if exists( select * from sysobjects where id = object_id('dbo.spFastMovingItem'))
	begin
		drop procedure spFastMovingItem
	end
GO

-------------------------------------------------------------------------------  
--created by  :Anoop  
  
-- Procedure Name : spFastMovingItem  
--description :To select items which dave been sold more than a quantity limit  
--       :Olny for Touch Screen POS  
--i/o       :@numQtylimit =quantity limit  
--o/p       :fastmovong items sold quantity >@numQTYlimit  
-------------------------------------------------------------------------------  
  
  
CREATE   procedure spFastMovingItem   
(  
@numQtylimit as numeric(18,3),  
@shopid as numeric(18)  
)  
as  
begin  
CREATE TABLE #tempsumofqty  
  (  
 qty   numeric(18,2),  
 itemid numeric(18)  
 )   
 insert into #tempsumofqty   
 select sum(posdquantity) qty,posditemid itemid  
 from       vwShopItemSales   
 where      poshshopid=@shopid  
 group by   posditemid  
  
 select  dsc.itemid,dsc.code itemcode,dsc.itemdescription   
 from    #tempsumofqty iid,vwItemDescription dsc   
 where   iid.qty>@numQtylimit and dsc.itemid=iid.itemid  
 order by iid.qty  
 drop table #tempsumofqty  
  
end
GO  
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
if exists( select * from sysobjects where id = object_id('dbo.spGdnNonMovingItems'))
	begin
		drop procedure spGdnNonMovingItems
	end
GO

--spGdnNonMovingItems '20070101','20080105',5,50,1000,'D','',30          
 /****** Object:  Stored Procedure dbo.spGdnNonMovingItems    Script Date: 18/01/2003 9:45:42 PM ******/              
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
    
------------------------------------------------------              
-- created by  : Hariharan               
-- created date : 13/12/2002              
-- Comments : V3              
--------------------------------------------------------------------------------------              
-- Modified on  : 13/04/2009                
-- Modified by  : Regin T.              
-- Comments   : User is enabled to select more than one godown in the HQ Reports interface.           
--     So this SP is modified to accept a list of Godown IDs as input.           
--    Input argument @intGodownId is modified as @strGodownID.          
-------------------------------------------------------------------------------------- 
--Ref.No.1
-- Modified on  : 31/05/2012                
-- Modified by  : AADYAKUMAR.D.V              
-- Comments     : Added new columns  cost price,current stock        
--------------------------------------------------------------------------------------                
--spGdnNonMovingItems '20120322','20120422', 50,0, 'F','7','',0       
create PROC spGdnNonMovingItems @strStartDate AS VarChar(10), @strToDate AS VarChar(10),              
@NoOfRecords AS int, @QuantityLimit AS Numeric(18, 3),               
@MoveType AS Char(1) , @strGodownID AS varchar(250), @strBrand as varchar(250) ='',@NoOfBackDays as int=0  AS              
--              
BEGIN              
 set nocount on              
    CREATE TABLE #gdnItemStockStart              
 (              
  GodownId int,              
  itemid int,              
  sdstock numeric(18,2),              
   edstock numeric(18,2),              
   transstock numeric(18,2)             
  )              
              
 CREATE TABLE #gdnItemStockEnd              
 (              
   GodownId int,              
  itemid int,              
  sdstock numeric(18,2),              
  edstock numeric(18,2),              
  transstock numeric(18,2)             
  )              
 CREATE TABLE #gdnItemStockTrans              
 (              
   GodownId int,              
   itemid int,              
   sdstock numeric(18,2),              
   edstock numeric(18,2),              
   transstock numeric(18,2)             
  )              
 CREATE TABLE #gdnItemStock              
 (              
   GodownId int,              
   itemid int,              
   sdstock numeric(18,2),              
   edstock numeric(18,2),              
   transstock numeric(18,2)              
  )              
 declare @strWhere as varchar(250)              
 declare @strSql as nvarchar(4000)              
 declare @strTop as varchar(250)              
 declare @strBrandCondition as varchar(250)             
 declare @dtMaxBillDateforDead as char(8)             
 declare @strGodCond as varchar(250) -- String Godown Condition        
        
  if @strGodownID <> ''        
    set @strGodCond = ' in (' + @strGodownID + ')'        
  else        
    set @strGodCond = ' not in (-1)' -- To get records of all godowns        
        
 -- get starting stock (stock at the start date)              
         
 set @strSql = N'select gsGodownId, vw.gsItemId, sum(transqty * mode),               
     0.0, 0.0  from vwGdnBinCardWithOpening vw              
     WHERE (sDate <''' +                
     @strStartDate + ''' or sdate is null) and gsGodownId'               
     + @strGodCond +   -- + @strWhere +               
     ' group by gsGodownId, vw.gsItemId '              
        
              
 -- insert the starting stock to gdnItemStockStart              
 insert into #gdnItemStockStart  exec sp_Executesql @strSql              
              
 -- Get the ending stock (stock at the end date)              
 set @strSql = N'select gsGodownId, vw.gsItemId, 0.0, sum(transqty * mode),               
     0.0  from vwGdnBinCardWithOpening vw              
     WHERE (sdate <= ''' +               
     @strtodate + ''' or sdate is null) and gsGodownId' +               
     @strGodCond +  -- + @strWhere +               
     'group by gsGodownId, vw.gsItemId'      
               
              
 -- insert ending stock to gdnItemStockEnd              
 insert into #gdnItemStockEnd exec sp_Executesql @strSql              
              
 -- get transaction qty              
 set @strSql = N'select gsGodownId, vw.gsItemId, 0.0,  0.0, sum(TransQty)                
     from vwGdnBinCardWithOpening vw               
     WHERE (sdate >= ''' +                
     @strStartDate + '''and sdate <= ''' +  @strtodate + ''' )               
      and gsGodownId ' + @strGodCond + --@strWhere +               
     ' and (type = ''Despatch To Shop'' OR               
     type = ''Special Despatch'')              
     group by gsGodownId, vw.gsItemId'               
 --print @strSql              
 -- insert transation qty to gdnItemStockTrans 
               
 insert into #gdnItemStockTrans  exec sp_Executesql @strSql              
     --print 'ddddd'           
  -- Then bring starting stock, ending stock and transaction qty to gdnItemStock              
 insert into #gdnItemStock select GodownId, itemid, sum(sdstock), sum(edstock),               
   sum(transstock) from (              
   select GodownId, itemid, sdstock, edstock, transstock               
   from #gdnItemStockStart              
   union all              
   select GodownId, itemid, sdstock, edstock, transstock               
   from #gdnItemStockEnd              
   union all              
   select GodownId, itemid, sdstock, edstock, transstock               
   from #gdnItemStockTrans) a              
   group by GodownId, itemid              
           
 if @MoveType = 'F'               
  begin              
   set @strWhere = ' AND TransStock >= ' +              
      convert(varchar, @QuantityLimit) +               
     ' AND TransStock > 0' +               
     ' ORDER BY TransStock DESC '              
   set @strTop = 'TOP ' + convert(VarChar, @NoOfRecords)              
  end              
 else if @MoveType = 'S'              
  begin              
   if @QuantityLimit = 0               
    begin              
     set @strWhere = ' AND TransStock > 0' +               
       ' ORDER BY TransStock ASC'              
    end               
   else                 
    begin              
     set @strWhere = ' AND TransStock <= ' +               
       convert(varchar, @QuantityLimit) +              
                                          ' AND TransStock > 0' +               
       ' ORDER BY TransStock ASC'              
    end              
   set @strTop = 'TOP ' + convert(VarChar, @NoOfRecords)              
  end              
 else if @MoveType = 'D'              
  begin              
   set @strWhere = ' AND edStock > 0 AND TransStock = 0'              
   set @strTop = ''              
  end               
if @strBrand<>''            
 set @strBrandCondition = ' and i.Brand =''' + @strBrand +''' '            
else            
  set @strBrandCondition=''    
          
--Ref.No.1---START---              
 --set @strSql = N'select vw1.* from(select ' + @strTop + ' s.*, u.unitname, ic.itemcategoryid, ic.CategoryNameDescription,               
 --  vw.ItemDescription, i.brand, i.itemcode               
 --  from aItem i, aItemCategory ic, aunit u, vwItemDescription vw,               
 --  #gdnItemStock s               
 --  where vw.itemid = s.itemid and s.itemid = i.itemid               
 --  and i.ItemCategoryID = ic.ItemCategoryID and               
 --  u.unitid = i.unitsid ' + @strBrandCondition + @strWhere + ')vw1 '  
 
  set @strSql = N'select vw1.* from(select ' + @strTop + ' s.*, u.unitname, ic.itemcategoryid, ic.CategoryNameDescription,               
   vw.ItemDescription, i.brand, i.itemcode,i.itemrate,
   (SELECT gsstock from vwInquirygodownStock where gsitemid=i.itemid and gsgodownid=godownid ) stock                 
   from aItem i, aItemCategory ic, aunit u, vwItemDescription vw,               
   #gdnItemStock s               
   where vw.itemid = s.itemid and s.itemid = i.itemid               
   and i.ItemCategoryID = ic.ItemCategoryID and               
   u.unitid = i.unitsid ' + @strBrandCondition + @strWhere + ')vw1 '          
--Ref.No.1----END----     
     
---Added by: Sreekanth.M.V            
---Purpose : Dead Items whose bill da date less than (Todate-@NoOfDays) are only shown           
           
if @MoveType = 'D'            
begin            
 set @dtMaxBillDateforDead=(select convert(varchar(8),dateadd("d",-@NoOfBackDays,convert(datetime,@strToDate,120)),112))            
            
            
             
 set @strSql=@strSql + 'inner join            
 (            
 select max(vw.maxbilldate) maxbilldate,vw.itemid from (select max(pbhbilldate) maxbilldate,pbditemid itemid from LOspPurchaseBillheader lph             
 inner join LOspPurchaseBillDetail lpd             
 on lph.pbhbillid=lpd.pbdbillid and lph.pbhcancelled=0            
 group by pbditemid            
                   
 union             
        
 select max(lphbilldate) maxbilldate,lpditemid itemid from LOslocalpurchaseheader lph             
 inner join LosLocalPurchaseDetail lpd on            
 lph.lphbillid=lpd.lpdbillid and lph.lphcancelled=0            
 group by lpditemid) vw            
 group by vw.itemid            
 ) vw2 on vw1.itemid=vw2.itemid             
     and vw2.maxbilldate<''' + @dtMaxBillDateforDead + ''''            
            
end            
            
              
print @strSql              
             
 exec sp_executeSql @strSql              
              
 drop table #gdnItemStockStart              
 drop table #gdnItemStockEnd              
 drop table #gdnItemStockTrans              
 drop table #gdnItemStock              
 set nocount off              
end            

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
if exists( select * from sysobjects where id = object_id('dbo.spHPDebtorAgeRecivableDifference'))
	begin
		drop procedure spHPDebtorAgeRecivableDifference
	end

GO
--exec spHPDebtorAgeRecivableDifference '20110101','20111231'
-- =============================================
-- Author:		AADYAKUMAR.D.V
-- Create date: 09/07/2012
-- Description:	Find out the reason for not tallying HP Debtor age analysis and HP Recivables(GL)
-- =============================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure spHPDebtorAgeRecivableDifference 
(@dtstartdate as varchar(11),
 @dtenddate as varchar(11))
as
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
	SET NOCOUNT ON;
--	Table variable to store HP Debtor age analaysis
declare @tmpAge TABLE (
invamt numeric(18,8),
settleamt numeric(18,8),
invoiceid  int,
customerid int,
shopid int,
due	varchar(7),
invoicedate datetime,
invoiceno VARCHAR(50),	
type varchar(4),	
remarks	VARCHAR(1000),
customername VARCHAR(1000),
currencyname VARCHAR(1000),
symbol VARCHAR(1000),
duedate datetime, 
overduedays datetime,
address1 VARCHAR(1000),	
address2 VARCHAR(1000),
address3 VARCHAR(1000),
referenceno VARCHAR(1000),
debtoraccid	int,
accountdesc VARCHAR(1000),
CustomerCategory VARCHAR(1000))
--	Table variable to store HP Recivables posting
declare @tmpPosting TABLE (
JournalID int,
CompanyID int,
JournalDate datetime,
remarks	varchar(1000),
departmentID int,	
referenceno	varchar(50),
financialID int,
type varchar(10),	
Amount numeric(18,8),
particulars	varchar(250),
journalcredit int,	
prefix	varchar(10),
updatetime datetime,
depamount numeric(18,8),
actualamount numeric(18,8)
)

declare @intAccid as int
declare @intCompanyid as int 
select @intAccid = DebtorAcc from aHPAccountsSettings
select @intCompanyid = CompanyID from aHPAccountsSettings

Insert into @tmpAge  Exec spHPDebtorAgeSum '',@dtenddate,'',0,0,'',0,''

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[HPDebtorAge]') AND type in (N'U'))
begin
DROP TABLE [dbo].[HPDebtorAge]
end
--  Store HP Debtor age report out put
select * into HPDebtorAge from(select * from @tmpAge A ) vw

Insert into @tmpPosting  EXEC spPostings @intCompanyid,@intAccid,0,@dtenddate

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[HPPosting]') AND type in (N'U'))
begin
DROP TABLE [dbo].[HPPosting]
end
--  Store HP Recivable report(GL) out put
select * into HPPosting from(select * from @tmpPosting P ) vw

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[HPDebtorAgeRecivableDifference]') AND type in (N'U'))
begin
DROP TABLE [dbo].[HPDebtorAgeRecivableDifference]
end
--  Compare HP Recivable values and HP Debtor age values
select * into HPDebtorAgeRecivableDifference from(
select invoiceno,Invamt,A.type DAAType,p.referenceno,Amount,Amount-invamt balance,P.type JournalType,JournalDate  
from @tmpAge A inner join @tmpPosting P on invoiceno=p.referenceno and Amount<>Invamt) vw

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[HPUnPostedTransaction]') AND type in (N'U'))
begin
DROP TABLE [dbo].[HPUnPostedTransaction]
end
--  Getting unposted Items
select * into HPUnPostedTransaction from(
select invoiceno,Invamt,A.type DAAType,p.referenceno,Amount,Amount-invamt balance,P.type JournalType,invoicedate  
from @tmpAge A left outer join @tmpPosting P on invoiceno=p.referenceno where p.referenceno is null) vw

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[HPNotIncludedTransactions]') AND type in (N'U'))
begin
DROP TABLE [dbo].[HPNotIncludedTransactions]
end
--  Getting Transaction not included in Debtor age analysis
select * into HPNotIncludedTransactions from(
select p.referenceno,Amount,P.type JournalType,invoiceno,Invamt,A.type DAAType,Amount-invamt balance,JournalDate 
from @tmpAge A right outer join @tmpPosting P on invoiceno=p.referenceno where invoiceno is null and Amount<>0) vw

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[HPRecivablesPosting]') AND type in (N'U'))
begin
DROP TABLE [dbo].[HPRecivablesPosting]
end
--  Getting Transaction Not showing in other senario
select * into HPRecivablesPosting from(
select h.referenceno,h.JournalDate,case when h.Type='J' then 'Journal' else h.Type end JournalType,AccountID,JournalCredit,Amount 
from MOaJournalHeader h inner join MOaJournalDetails d 
on h.JournalID=d.JournalID and d.AccountID=@intAccid and h.Cancel=0
and JournalDate<=@dtenddate 
and (ReferenceNo not in 
(select ReferenceNo from HPDebtorAgeRecivableDifference
union all
 select ReferenceNo from HPNotIncludedTransactions
 union all
 select p.referenceno  
from HPDebtorAge A inner join HPPosting P on invoiceno=p.referenceno and Amount=Invamt)
)
) vw

END
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Added latest stored procedure SendEmails collcted from SIMDI
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO   
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SendEmails]') AND type in (N'P', N'PC'))
BEGIN
	DROP PROCEDURE SendEmails
END
GO  
-- Procedure
-- =============================================                  
-- Author:  Rajesh Kamalakshan                  
-- Create date: 06-06-2009                  
-- Description: For sending emails to customers                  
-- =============================================    
-- Reference : RefNo-1  
-- Upgraded By: Regin T.  
-- Upgraded On: 18-06-2010  
-- Upgrade: Attached the statement of accounts in all mails.  
-- =============================================   
             
CREATE PROCEDURE [dbo].[SendEmails] --1                  
 -- Add the parameters for the stored procedure here                  
 @CompanyID as int                  
AS                  
BEGIN                  
 -- SET NOCOUNT ON added to prevent extra result sets from                  
 -- interfering with SELECT statements.                  
 SET NOCOUNT ON;                 
create table #MailList                
(CustomerId int                
,DepartmentID int                
,DepartmentName varchar(50)                
,InvocieId int                
,InvAmount numeric(18,2)                
,SettledAmt numeric(18,2)                
,BalanceAmt numeric(18,2)                
,Age int                
,Due char(10)                
,Processed bit                
,CurrencyName varchar(50)                
,Symbol varchar(20)  
,Invoicedate datetime  
,Invoiceno varchar(50)  
,Referenceno varchar(100)  
,remarks varchar(1000))                
                
create table #Departments                
(departmentid int                 
)                
                
                
insert into #MailList select * from  dbo.EmailList --where age = 60                
                
                
                
--select * from #MailList                 
--drop table #MailList                
declare @customerid as int               
declare @amount as numeric(18,2)                

declare @CustomerName as varchar(100)                
declare @DuePeriod as int                
declare @EmailID as varchar(500)                
declare @currencysymbol as varchar(20)                
declare @body1 varchar(5000)                

declare @subject1 varchar(1000)                
declare @table as varchar(200)                
declare @Signature as varchar(2000)                
declare @Address1 varchar(250)                
declare @Address2 varchar(250)                
declare @Address3 varchar(250)                
declare @Address varchar(1000)                
declare @ccEmail varchar(2000)    
declare @cccEmail varchar(2000)       
declare @InchargeEmail varchar(2000)        
declare @departmentid int                
declare @departmentname varchar(50)                
declare @Profile as varchar(100)                
declare @Divisionhead as varchar(150)       
declare @XMLEmailList as xml   
declare @CustomerStatement as varchar(max)          

set @table='<table style="font-family: ''''Arial'''', Times, serif">'                

--set @table='<table style="font-family: ''''Courier New'''', Courier, monospace"><tr><td><img alt="" src="c:\editicon.png" /></td></tr>'                
set @cccEmail=''--Provide cc emailid                
set @subject1=''--Over Due Payments-             
set @profile=''--Automated Mail Service              
set @Divisionhead=''--Provide Incharge Name 
--Provide the corresponding information for below SIGNATURE parameter.               
/* set @Signature='<tr><td>Kind Regards<br>                
 <br>Enter Name                
 <br>Enter Designation,                
 <br>Enter Department Name,                
 <br>Enter Company Name,                
 <br>Address,                 
 <br>Address,                
 <br>Address,                
 <br>Address,                
 <br>Address.                
 <br>Mobile:                 
 <br>Fax	:                 
 <br>Phone	:                
 <br>E-mail	:                
 <br>Web	: '                
    +'</td></tr><tr><td><br><br><br><br> Fi-es Magnolia (The Complete Integrated Retail Business Management solution) http://www.fi-es.com</td></tr></table>'                
*/


while((select count(*) from #MailList )<>0 )                
begin                
 set @amount=0                
 set @EmailID=''--'rajesh.kamalakshan@fi-es.com;prasanth.joseph@fi-es.com'                
 select @customerid=max(customerid) from #MailList                
 select @EmailID=EmailId,@CustomerName=CustomerName,@Address1=Address1,@Address2=Address2,@Address3=Address3,@DuePeriod=Dueperiod from dbo.aCustomerMaster where CustomerID=@customerid and CompanyID=@CompanyId                
 set @Address='<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+@Address1+'</td></tr><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+@Address2+    
  '</td></tr><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+@Address3+'<br><br></td></tr>'                
 ---filtering the #MailList table by customerwise and assigning to another table #MailListCustomerwise                
 select * into #MailListCustomerwise from dbo.EmailList where customerid=@customerid                
 insert into #Departments select distinct departmentid from #MailListCustomerwise                
 while((select count(*) from #MailListCustomerwise)<>0)               
 begin         
  set @subject1='Over Due Payment-  '        
  set @ccEmail=''            
  set @Divisionhead=''      

  select @departmentid=max(departmentid)from #Departments        
  select  @InchargeEmail=InchargeEmail,@Divisionhead=InchargeName from adepartmentmaster where  departmentid=@departmentid and companyId=@CompanyID             
  set @ccEmail=@InchargeEmail+';'+@cccEmail    
      
  ------for preparing mail for the bills due before 10 days before due date                
  select @departmentname=DepartmentName,@amount=sum(balanceamt),@currencysymbol=symbol from dbo.#MailList where customerid=@customerid and age=@DuePeriod-10 and departmentid =@departmentid group by symbol,DepartmentName                
  if @amount>0                
  begin                
   set @body1 = @table+'<tr><td>Date '+cast( left(getdate(),11) as varchar(50))+'<br><br></td></tr><tr><td> '+@CustomerName +',<br><br></td></tr>'+@Address+                
   '<tr><td>This is a courtesy reminder to alert you of the upcoming payment of '+ @currencysymbol +' ' +cast(@amount as varchar(50)) +' due on or before  '+ cast( left( dateadd(day,@DuePeriod-(@DuePeriod-10),getdate() ),11)as varchar(50))   
  +'. Please find below the statement of accounts for your attention.' -- This line sdded by Regin (RefNo-1)  
  + ' If you have already sent    
 the payment please disregard this letter.<br><br></td></tr><tr><td>If you have any concerns or feel you may not be able to meet our credit terms, please contact us to discuss the situation, prior to the due date.<br><br></td></tr><tr><td>We thank you for
  
    
 your custom and look forward to your payment.<br><br></td></tr>'+@Signature          
    -- Added By Regin T. On 18-06-2010 (RefNo-1)  
    -- Generating customer statememt in html format   
    -- using the function ConvertCustomerStatementToHtml.  
 set @XMLEmailList=''  
 set @CustomerStatement=''  
 set @XMLEmailList=(select * from EmailList where CustomerId=@customerid and Age=@DuePeriod-10 order by Age  desc FOR XML AUTO)  
 select @CustomerStatement=dbo.FnConvertCustomerStatementToHtml(@XMLEmailList)   
 set @body1=@body1+'<br><br>'+@CustomerStatement  
    -- Ends Here  
   set @subject1=@subject1+@DepartmentName        
   EXEC msdb.dbo.sp_send_dbmail @recipients=@EmailID,@copy_recipients=@ccEmail,                
   @subject = @subject1,                
   @body = @body1,                
   @body_format = 'HTML',                
   @profile_name=@profile,@importance ='High'                
  end                
  --------------------------------------------------------------------------------------------------------------                
  ------for preparing mail for the bills due on due date                
  set @subject1='Over Due Payment-  '      
  set @amount=0                
  select @departmentname=DepartmentName,@amount=sum(balanceamt) ,@currencysymbol=symbol from dbo.#MailList where customerid=@customerid and age=@DuePeriod and departmentid =@departmentid group by symbol,DepartmentName                
                     
  if @amount>0                
  begin                
   set @body1 = @table+'<tr><td>Date '+cast( left(getdate(),11) as varchar(50))+'<br><br></td></tr><tr><td> '+@CustomerName +',<br><br></td></tr>'+@Address+                
   '<tr><td>We note that the amount of  '+ @currencysymbol +' ' +cast(@amount as varchar(50)) +' is due for payment by today;'+ cast( left( getdate() ,11)as varchar(50))   
   +'. Please find below the statement of accounts for your attention.' -- This line sdded by Regin (RefNo-1)  
   +' If you have already sent payment or will be making payment today please disregard '+    
   'this letter.<br><br></td></tr><tr><td>In the event that you are unable to meet our credit terms or have any concerns regarding the  payment, please contact us immediately to discuss the situation.<br><br></td></tr> '+         
   '<tr><td>We thank you for your custom and look forward to a mutually beneficial ongoing relationship.Looking forward to receive the payment at your earliest.<br><br></td></tr>'+@Signature                
    -- Added By Regin T. On 18-06-2010 (RefNo-1)  
    -- Generating customer statememt in html format   
    -- using the function ConvertCustomerStatementToHtml.  
 set @XMLEmailList=''  
 set @CustomerStatement=''  
 set @XMLEmailList=(select * from EmailList where CustomerId=@customerid and Age=@DuePeriod order by Age  desc FOR XML AUTO)  
 select @CustomerStatement=dbo.FnConvertCustomerStatementToHtml(@XMLEmailList)   
 set @body1=@body1+'<br><br>'+@CustomerStatement  
    -- Ends Here  
   set @subject1=@subject1+@DepartmentName        
   EXEC msdb.dbo.sp_send_dbmail @recipients=@EmailID,@copy_recipients=@ccEmail,                
   @subject = @subject1,                
   @body = @body1,                
   @body_format = 'HTML',                
   @profile_name=@profile,@importance ='High'                
  end                
  --------------------------------------------------------------------------------------------------------------                
  ------for preparing mail for the bills due on 60 th day   with copy       
  set @subject1='Over Due Payment-  '            
  set @amount=0                
  select @departmentname=DepartmentName,@amount=sum(balanceamt) ,@currencysymbol=symbol from dbo.#MailList where customerid=@customerid and age = 60  and departmentid =@departmentid group by symbol,DepartmentName                
  if @amount>0                
  begin                
   set @body1 = @table+'<tr><td>Date '+cast( left(getdate(),11) as varchar(50))+'<br><br></td></tr><tr><td> '+@CustomerName +',</td></tr>'+@Address+      
   '<tr><td>Dear Sir / Madam,<br><br></td></tr><tr><td><u>Sub:Over Due Payments –  '+@departmentname+'</u><br><br></td></tr> <tr><td>Our records show that you have an overdue payment of  '+ @currencysymbol +' ' +cast(@amount as varchar(50)) +    
   '.Please find below the statement of accounts for your attention. <br><br></td></tr><tr><td>Our credit facilities are 30 days and the above amount is now more than 60 days past due.<br><br></td></tr><tr><td> Please contact Mr. '+@Divisionhead+' or the 
undersigned'+    
   ', if there is a problem with any of the invoices or you are unable to make  immediate payment. Otherwise, we await your  settlement in the next few days.<br><br></td></tr>  '+    
   '<tr><td>Thanking you in advance for your immediate attention to this request.<br><br></td></tr>'+@Signature      
 --Generating customer statememt in html format using the function ConvertCustomerStatementToHtml  
 set @XMLEmailList=''  
 set @CustomerStatement=''  
 set @XMLEmailList=(select * from EmailList where CustomerId=@customerid and Age=60 order by Age  desc FOR XML AUTO)  
 select @CustomerStatement=dbo.FnConvertCustomerStatementToHtml(@XMLEmailList)   
 set @body1=@body1+'<br><br>'+@CustomerStatement  
   set @subject1=@subject1+@DepartmentName        
   EXEC msdb.dbo.sp_send_dbmail @recipients=@EmailID,@copy_recipients=@ccEmail,                
   @subject = @subject1,                
   @body = @body1,                
   @body_format = 'HTML',                
   @profile_name=@profile,@importance ='High'--,@file_attachments ='c:\aa.xml'                
  end                
  --------------------------------------------------------------------------------------------------------------                
  ------for preparing mail for the bills due on 75th day   with copy             
  set @subject1='Over Due Payment-  '      
  set @amount=0                
  select @departmentname=DepartmentName,@amount=sum(balanceamt) ,@currencysymbol=symbol from dbo.#MailList where customerid=@customerid and age = 75 and departmentid =@departmentid group by symbol,DepartmentName                
  if @amount>0                
  begin                
   set @body1 = @table+'<tr><td>Date '+cast( left(getdate(),11) as varchar(50))+'<br><br></td></tr><tr><td> '+@CustomerName +',<br><br></td></tr>'++@Address+                
   '<tr><td>Dear Sir / Madam,<br><br></td></tr><tr><td><u>Sub:  Over Due Payments –  '+@departmentname+'</u><br><br></td></tr><tr><td> If you have already settled this account, please disregard this letter. <br><br></td></tr><tr><td>Our records show that 
  
'+    
   'you have an overdue payment of  '+ @currencysymbol +' ' +cast(@amount as varchar(50)) +'. We have previously forwarded a statement of accounts for your attention, and once again, we attach a copy.<br><br></td></tr>'+               
   '<tr><td>Our credit facilities are 30 days and the above amount is now more than 75 days past due.<br><br></td></tr><tr><td> If there is a problem to this account, please bring this to our attention by making immediate contact with the undersigned.<br>
  
'+    
   '<br></td></tr><tr><td>In order to ensure this matter goes no further please make immediate payment or contact us as requested.<br><br></td></tr>'+@Signature                
  
 --Generating customer statememt in html format using the function ConvertCustomerStatementToHtml  
 set @XMLEmailList=''  
    set @CustomerStatement=''  
 set @XMLEmailList=(select * from EmailList where CustomerId=@customerid and Age=75 order by Age  desc FOR XML AUTO)  
 select @CustomerStatement=dbo.FnConvertCustomerStatementToHtml(@XMLEmailList)     
 set @body1=@body1+'<br><br>'+@CustomerStatement  
   set @subject1=@subject1+@DepartmentName        
   EXEC msdb.dbo.sp_send_dbmail @recipients=@EmailID,@copy_recipients=@ccEmail,                
   @subject = @subject1,                
   @body = @body1,          
   @body_format = 'HTML',                
   @profile_name=@profile,@importance ='High'                
  end                
  --------------------------------------------------------------------------------------------------------------                
  ------for preparing mail for the bills due on 90th day  
 set @subject1='Over Due Payment-  '           
  set @amount=0                
  select @departmentname=DepartmentName,@amount=sum(balanceamt) ,@currencysymbol=symbol from dbo.#MailList where customerid=@customerid and age = 90 and departmentid =@departmentid group by symbol,DepartmentName                
  if @amount>0                
  begin                
   set @body1 = @table+'<tr><td>Date '+cast( left(getdate(),11) as varchar(50))+'<br><br></td></tr><tr><td> '+@CustomerName +',<br><br></td></tr>'+@Address+                
   '<tr><td>Dear Sir / Madam,<br><br></td></tr><tr><td><u>Sub:  Over Due Payments –  '+@departmentname+'<br><br></u><br><br></td></tr><tr><td> Please ignore this letter if you have already settled the account. <br><br></td></tr><tr><td>Our records show t 
 
hat'+    
   'you have an overdue debt of   '+ @currencysymbol +' ' +cast(@amount as varchar(50))   
   +'. We attach the statement of accounts for your attention.' -- This line added by Regin (RefNo-1)  
   +'<br><br></td></tr>'+          
   '<tr><td>Our credit facilities are 30 days and the above amount is now more than 90 days past due.<br><br></td></tr><tr><td> We have contacted you on numerous occasions to finalize this outstanding.<br><br></td></tr><tr><td>If we have not received pay
m  
ent'+    
   'or contact from you within 7 days we will be forced to hand the matter to our solicitors and suspend your credit facility with all SIMDI Company divisions. It is a drastic step that we would like to avoid.<br><br></td></tr>'+            
   '<tr><td>Looking forward to settling this matter at the earliest.<br><br></td></tr>'+@Signature          
    -- Added By Regin T. On 18-06-2010 (RefNo-1)  
    -- Generating customer statememt in html format   
    -- using the function ConvertCustomerStatementToHtml.  
 set @XMLEmailList=''  
 set @CustomerStatement=''  
 set @XMLEmailList=(select * from EmailList where CustomerId=@customerid and Age=90 order by Age  desc FOR XML AUTO)  
 select @CustomerStatement=dbo.FnConvertCustomerStatementToHtml(@XMLEmailList)   
 set @body1=@body1+'<br><br>'+@CustomerStatement  
    -- Ends Here  
   set @subject1=@subject1+@DepartmentName              
   EXEC msdb.dbo.sp_send_dbmail @recipients=@EmailID,@copy_recipients=@ccEmail,                
   @subject = @subject1,                
   @body = @body1,                
   @body_format = 'HTML',                
   @profile_name=@profile,@importance ='High'                
  end                
  --------------------------------------------------------------------------------------------------------------                
  ------for preparing mail for the bills due on 100th day  
  set @subject1='Over Due Payment-  '             
  set @amount=0                
  select  @departmentname=DepartmentName,@amount=sum(balanceamt) ,@currencysymbol=symbol from dbo.#MailList where customerid=@customerid and age = 100 and departmentid =@departmentid group by symbol,DepartmentName                
  if @amount>0                
  begin                
   set @body1 = @table+'<tr><td>Date '+cast( left(getdate(),11) as varchar(50))+'<br><br></td></tr><tr><td> '+@CustomerName +',<br><br></td></tr>'++@Address+                
   '<tr><td>Dear Sir / Madam,<br><br></td></tr><tr><td><u>Sub:  Over Due Payments –  '+@departmentname+'</u><br><br></td></tr> <tr><td>If you have already settled the account please ignore this letter. <br><br></td></tr><tr><td>Our records show that you '
  
+    
   'have an overdue debt of   '+ @currencysymbol +' ' +cast(@amount as varchar(50))   
   +'. We attach the statement of accounts for your attention.' -- This line added by Regin (RefNo-1)  
   +'<br><br></td></tr>'+            
   '<tr><td>Our credit facilities are 30 days and the above amount is now more than 100 days past due.<br><br></td></tr><tr><td> We have contacted you on numerous occasions to finalize this outstanding.<br><br></td></tr><tr><td>Since you have failed to'+ 
  
   
   ' make payment or contact us to discuss the outstanding amount,please be advised that the matter is now in the hands of our solicitors.<br><br></td></tr><tr><td>Please also note that at the above date your credit facility, with all COMPANY NAME has '+    
   ' been suspended.<br><br></td></tr><tr><td>We greatly regret having to take these steps, however your refusal to settle or discuss this debt has left us with no alternative course of action.<br><br></td></tr>    '+    
   '<tr><td>Should you wish to try to retrieve this situation and protect your business reputation you may still contact us and arrange payment directly.<br><br></td></tr><tr><td>Looking forward to your payment and to settle the matter amicably.<br><br></
  
td></tr>'    
   +@Signature                
    -- Added By Regin T. On 18-06-2010 (RefNo-1)  
    -- Generating customer statememt in html format   
    -- using the function ConvertCustomerStatementToHtml.  
 set @XMLEmailList=''  
 set @CustomerStatement=''  
 set @XMLEmailList=(select * from EmailList where CustomerId=@customerid and Age=100 order by Age  desc FOR XML AUTO)  
 select @CustomerStatement=dbo.FnConvertCustomerStatementToHtml(@XMLEmailList)   
 set @body1=@body1+'<br><br>'+@CustomerStatement  
    -- Ends Here  
   set @subject1=@subject1+@DepartmentName        
   EXEC msdb.dbo.sp_send_dbmail @recipients=@EmailID,@copy_recipients=@ccEmail,                
   @subject = @subject1,                
   @body = @body1,                
   @body_format = 'HTML',                
   @profile_name=@profile,@importance ='High'                
  end                
  --------------------------------------------------------------------------------------------------------------                
 delete from #MailListCustomerwise where departmentid=@departmentid                
 delete from #Departments where departmentid =@departmentid                
 end                
    delete from #Departments                
 drop table  #MailListCustomerwise                 
 delete from #MailList where customerid=@customerid                 
--select * from #MailList                
--print @body1                
end                
END                  
                
--msdb.dbo.sysmail_start_sp
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
 
 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDebtorAgeSumDetailed]') AND type in (N'P', N'PC'))
  Drop Procedure spDebtorAgeSumDetailed
go
 --***************************************************************************************************          
-- Created by  :  Nidheesh P V          
-- Created on  : 06/07/2011            
-- Purpose     : To Get Debtor Age For  0 - 15,16 - 30 ,31 - 60, 61 - 120,121 - 240,241 - 365     
--and to display the customer even if the customer has no invoice/settlement but an advance is there.     
--Used in the reprot Debtor Age Analysis with Advance     
--Ref No : Ref-No1  
--***************************************************************************************************  
--- Modified by : Jyothish SR     
-- Modified on : 27/03/2012     
-- Purpose     : Avoid Select * statement in vwinvoices and  vwsettlements
  
--spDebtorAgeSumDetailed '20101231','20111231','9723',0,0,0,'',''    
      
             
create  PROCEDURE spDebtorAgeSumDetailed (@dtstartdate varchar(11),@dtinvdate as varchar(11),                  
@intcustid varchar(1000),@intdepartid int,@intageTodate int=0 ,@intShopID int=0 ,            
@strCatName as Varchar(30)='', @strGroupName as Varchar(30)=''  )                  
as                  
set ansi_Warnings off                  
set nocount on                  
begin                  
  Create table #tmpInvoices (CompanyID int,                   
shopid int,                   
DepartmentID int,                   
InvoiceID int,                   
customerid int,                   
invoicedate datetime,                   
invoiceno varchar(50),                   
Referenceno varchar (100),                  
remarks varchar(1000),                   
InvAmt numeric(18,2),                   
Due varchar(12),                   
Type varchar(4),                   
Debtortype varchar(50),                   
updatetime datetime,                   
CustomerCategory varchar(100),                  
duedate datetime ,                  
depexrate numeric(18,2) ,                  
InterFaceID int ,                  
SalesPersonID int  ,                  
CustomerType char(1),                   
DutyAmt numeric(18,2) ,                  
CostPrice numeric(18,4),            
CustGroupName varchar(100),                 
age int            
)                   
                  
Create Table #tmpSettlements                   
(customerid int,                   
ReceiptNo varchar(50),                  
companyid int,                   
invoiceid int,                   
shopid int,                   
settleddate datetime,                   
departmentid int,                   
settledamt numeric(18,2),                  
Type varchar(50))                  
                  
                  
 declare @strquery as nvarchar(4000)                  
 declare @SettleCustId as varchar(1500), @Invcustid as varchar(1500)                  
 declare @strShop as nvarchar(4000)             
 declare  @strCatCond as Varchar(300)            
 declare @strGroupCond as Varchar(300)                    
             
 SET @SettleCustId = ''                  
 set @Invcustid = ''                  
 set @strShop = ''             
 set @strCatCond=''            
 set @strGroupCond=''            
 set @intageTodate=1              
if @strCatName<>''            
set @strCatCond = ' CustomerCategory = ''' + @strCatName + ''' And '            
            
if @strGroupName<>''            
set @strGroupCond = ' CustGroupName = ''' + @strGroupName + ''' And '            
            
            
if @intShopID > 0             
Begin            
 set @strShop=' And  #tmpInvoices.shopid = ' + cast(@intShopID As varchar)            
end             
 if @intcustid<>''    --hari given to handle with out customerid also                  
 Begin                  
  set @SettleCustId = ' customerid in (' + @intcustid + ') and'                    
  set @Invcustid = 'vwInvoices.customerid in (' + @intcustid + ') and'                        
 End                   
 if @dtstartdate =''                  
  Begin                  
  if @intdepartid >0                  
   set @strquery ='insert #tmpInvoices                  
    Select  CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,Referenceno,remarks,InvAmt,Due,Type,Debtortype,
    updatetime,CustomerCategory,duedate,depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,CostPrice,
    CustGroupName,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                  
    ' invoicedate <=''' + @dtinvdate + '''' +                   
   ' and departmentid = ' + cast(@intdepartid as varchar)                   
  else                  
   set @strquery ='insert #tmpInvoices                  
    Select  CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,Referenceno,remarks,InvAmt,Due,Type,Debtortype,
    updatetime,CustomerCategory,duedate,depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,CostPrice,
    CustGroupName,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                   
    ' invoicedate <=''' + @dtinvdate + ''''                  
  End                  
  Else                  
  Begin                   
  if @intdepartid >0                  
   set @strquery ='insert #tmpInvoices                  
    Select  CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,Referenceno,remarks,InvAmt,Due,Type,Debtortype,
    updatetime,CustomerCategory,duedate,depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,CostPrice,
    CustGroupName,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                   
    ' invoicedate <=''' + @dtinvdate + '''' +                   
   ' and departmentid = ' + cast(@intdepartid as varchar) +                   
   ' and invoicedate >=''' + @dtstartdate + ''''                  
  else                  
   set @strquery ='insert #tmpInvoices                  
    Select  CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,Referenceno,remarks,InvAmt,Due,Type,Debtortype,
    updatetime,CustomerCategory,duedate,depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,CostPrice,
    CustGroupName,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                   
    ' invoicedate <=''' + @dtinvdate + '' +                   
   ''' and invoicedate >=''' + @dtstartdate + ''''                  
  End                  
  exec sp_Executesql @strquery    
-------Ref-No1----------------------------------------------------------  
--to display the customer even if the customer has no invoice/settlement but an advance is there.       
  
INSERT INTO #tmpInvoices   
select   
ad.companyid,ad.Shopid,ad.departmentid,'',ad.customerid,ad.invoicedate,  
'','',  --refno  
'',  
ad.advance,  
0, --due  
'',  
'', --debtrtype  
'',  
ad.CustomerCategory,  
'',1,1,1,  
'',  --custtype  
1,   --dutyamnt  
1,   --costprice  
ad.custgroupname,  
0  
from vwcustomersummaryasdate ad    
LEFT OUTER JOIN #tmpInvoices inv ON ad.customerid=inv.customerid  
where inv.customerid is null   
and (ad.CustomerCategory in (@strCatName) or @strCatName='')  and (ad.custgroupname in( @strGroupName )  or @strGroupName='')          
and (ad.customerid in (@intcustid ) or @intcustid='')   
and (ad.departmentid in (@intdepartid) or @intdepartid=0)   
and (ad.Shopid in (@intShopID) or @intShopID=0)   
and (ad.invoicedate>=@dtstartdate or @dtstartdate='')            
and (ad.invoicedate<=@dtinvdate or @dtinvdate='')  
-----------------------------------------------------------------      
               
 if @dtstartdate =''                  
  Begin                  
  if @intdepartid >0                  
   set @strquery  = ' insert #tmpSettlements Select customerid,ReceiptNo,companyid,invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where ' + @SettleCustId +                   
   ' departmentid = ' + cast(@intdepartid as varchar) +                   
   ' and settleddate <=''' + @dtinvdate +  ''''                   
  else                  
   set @strquery  = 'insert #tmpSettlements  Select customerid,ReceiptNo,companyid,invoiceid,shopid,settleddate,departmentid,settledamt,Typefrom vwsettlements where ' + @SettleCustId +                   
   ' settleddate <=''' + @dtinvdate + ''''                    
                  
  End                  
  Else                  
  Begin                   
  if @intdepartid >0                  
   set @strquery  = ' insert #tmpSettlements Select customerid,ReceiptNo,companyid,invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where ' + @SettleCustId +                   
   ' departmentid = ' + cast(@intdepartid as varchar) +                   
   ' and settleddate <=''' + @dtinvdate +  '' +                   
   ''' and settleddate >=''' + @dtstartdate + ''''                  
  else                  
   set @strquery  = 'insert #tmpSettlements  Select customerid,ReceiptNo,companyid,invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where ' + @SettleCustId +                   
   ' settleddate <=''' + @dtinvdate + '' +                   
   ''' and settleddate >=''' + @dtstartdate + ''''                  
                  
  End                  
  exec sp_Executesql @strquery                   
                  
  set @strquery = 'SELECT  max(invamt) invamt,isnull(sum(settledamt),0) settleamt,#tmpInvoices.invoiceid,                  
   #tmpInvoices.customerid,#tmpInvoices.shopid,#tmpInvoices.due,#tmpInvoices.invoicedate ,                  
   #tmpInvoices.invoiceno,#tmpInvoices.type,remarks,customername,currencyname,symbol, #tmpInvoices.duedate,            
   datediff(dd,#tmpInvoices.duedate, ''' + @dtinvdate + ''' ) overduedays, address1, address2, address3,                   
   #tmpInvoices.referenceno,debtoraccid,b.accountdesc, aCustomerMaster.CustomerCategory,aCustomerMaster.CurrencyID FROM                   
       #tmpInvoices #tmpInvoices LEFT OUTER JOIN #tmpSettlements                    
   vwsettlements ON #tmpInvoices.customerid = vwsettlements.customerid AND                  
       #tmpInvoices.CompanyID = vwsettlements.companyid AND                  
       #tmpInvoices.InvoiceID = vwsettlements.invoiceid AND                  
       #tmpInvoices.type = vwsettlements.type AND                  
       #tmpInvoices.shopid = vwsettlements.shopid  and                   
   (vwsettlements.settleddate<=''' + @dtinvdate +                  
   ''' or vwsettlements.settleddate is null),                   
   aCurrencyMaster ,  aCustomerMaster, aAccountMaster b,exchangeratedetail                   
   WHERE #tmpInvoices.customerid = aCustomerMaster.CustomerID AND                  
       #tmpInvoices.CompanyID = aCustomerMaster.CompanyID and                   
   aCustomerMaster.CurrencyID = aCurrencyMaster.CurrencyID AND                  
       aCustomerMaster.CompanyID = aCurrencyMaster.CompanyID and                   
   aCustomerMaster.debtorAccID = b.AccountID ' + @strShop  + '                 
   and  #tmpInvoices.invoicedate<=''' + @dtinvdate + '''        
   and aCurrencyMaster.CurrencyID= exchangeratedetail.CurrencyID                     
   group by #tmpInvoices.invoiceid,#tmpInvoices.departmentid,                   
   #tmpInvoices.customerid, #tmpInvoices.shopid,due ,invoicedate,                   
   invoiceno,#tmpInvoices.type,remarks,                  
   customername,currencyname,symbol, #tmpInvoices.duedate,                   
   address1, address2, address3, #tmpInvoices.referenceno,                  
   debtoraccid,b.AccountDesc ,aCustomerMaster.CustomerCategory,aCustomerMaster.CurrencyID                  
   having max(invamt) <> sum(isnull(settledamt,0))'                  
                  
if @intageTodate=1                   
begin                  
 update #tmpInvoices set age=datediff(day,invoicedate,CONVERT(DATETIME, @dtinvdate,102))                   
 update #tmpInvoices set due =                  
   case when (age  >=0 and age <= 15) then '0 - 15'                   
  when (age  >=16 and age <= 30)  then '16 - 30'                    
  when (age  >=31 and age <= 60) then '31 - 60'            
  when (age  >=61 and age <= 90) then '61 - 90'     
  when (age  >=91 and age <= 120) then '91 - 120'         
  when (age  >=121 and age <= 240) then '121 - 240'          
  when (age  >=241 and age <= 365) then '241 - 365'               
  when (age  >=365) then ' > 365' else '' end                   
end                  
exec sp_Executesql @strquery                  
                  
drop table #tmpInvoices                  
drop table #tmpSettlements                  
end                  
set nocount off                  
set ansi_Warnings on 

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE adminv2
GO
IF EXISTS( SELECT * FROM SYSOBJECTS WHERE XTYPE='P' 
AND NAME='spDebtorAgeSum')
BEGIN
	DROP PROCEDURE spDebtorAgeSum
END
GO   

 
-- Modified by   : Kishore                                    
-- Modified on  : 10/06/2003                                    
-- Comments  : Added the Having condition in each select query                                    
--                        (on comparison with v2)                                    
                                    
-----------------------------------------------------------------------------                                    
-- Modified by   : venki, Hariharan R                                    
-- Modified on  : 11/09/2003 ....240903 (added debtoraccid ), 08/01/2004                                    
-- Comments  : given isnull --then 0 for settledamt field                                    
--                        (on comparison with v2)                                    
-- Modified by   : venkitesh                                    
-- Modified on  : 11/09/2003 ....240903 (added debtoraccid )                                    
-- Comments  : given vwSettlements as derived table filtering customerid, depid and invoicedate                                    
-- Modified by   : venkitesh  , Hariharan                                   
-- Modified on  : 29/06/2004, 08/12/2004                                      
-- Comments  : Corrected ageing and due period basis of todate                                    
--           : Corrected the company wise report fetching removing departmentid condition on settlements query                                        
-----------------------------------------------------------------------------                                    
-- RefNo-1                
-- Modified by : Regin                
-- Modified on : 16-06-2010                
-- Comments    : To speed up the execution.                
-- Old technique had below tow steps:                
--   1. Fetch ALL rows of vwInvoices and vwsettlements                 
--      into #tempvwInvoices and #tempvwsettlements respectively.                
--      Since all rows are fetched, it took huge time to complete.                
--   2. Required rows were fetched from #tempvwInvoices                 
--      and #tempvwsettlements applying condition.                
-- New technique eliminates the temporary tables and has one step:                
--   1. Required rows are fetched direcly from vwInvoices                 
--      and vwsettlements applying condition.                
--      Since rows are fetched on condition, fetch completes quickly.                
-- Time taken to generate the outstanding invoices report for one customer                
-- in Simdi DB is...                
--   In old technique: 3 Minues                
--   In new technique: 20 Seconds                
-----------------------------------------------------------------------------               
--RefNo:01            
--Modified By : VinothMurugan V.            
--Modified On : 06/08/2010            
--Purpose     : Adding Currencyid            
--------------------------------------------------------------------------
--Modified By : SHINE        
--Modified On : 28/07/2011        
--Purpose     : When added to VSS some unwaned comments came. So removed it                                   
--  spdebtoragesum '20010101','20100805','',0,0,0,'',''                             
 --RefNo:02
 --Modified By : Jyothish.SR.  
 -- Modified On : 27/03/2012     
 --Purpose     : select *  statement is avoid in vwsettlements and vwinvinvoices           
              
create  PROCEDURE dbo.spDebtorAgeSum (                                     
@dtstartdate varchar(11),@dtinvdate as varchar(11),                                      
@intcustid varchar(1000),@intdepartid int,@intageTodate int=0 ,@intShopID int=0 ,                                
@strCatName as Varchar(30)='', @strGroupName as Varchar(30)=''  )                                        
as                          
begin                      
 declare @strquery as nvarchar(4000)                                      
 declare @SettleCustId as varchar(1500), @Invcustid as varchar(1500)                                      
 declare @strShop as nvarchar(4000)                                 
 declare  @strCatCond as Varchar(300)                                
 declare @strGroupCond as Varchar(300)                        
                                 
 SET @SettleCustId = ''          
 set @Invcustid = ''                                      
 set @strShop = ''                                 
 set @strCatCond=''                                
 set @strGroupCond=''                          
                      
Create table #tmpInvoices (CompanyID int,                                       
shopid int,                                       
DepartmentID int,                 
InvoiceID int,                                       
customerid int,                                       
invoicedate datetime,                          
invoiceno varchar(50),                                       
Referenceno varchar (100),                                      
remarks varchar(1000),                                       
InvAmt numeric(18,2),                                       
Due varchar(7),                                       
Type varchar(7),                                       
Debtortype varchar(50),                                       
updatetime datetime,                                       
CustomerCategory varchar(100),                                      
duedate datetime ,                                      
depexrate numeric(18,2) ,                                      
InterFaceID int ,                                      
SalesPersonID int  ,                                      
CustomerType char(1),                                       
DutyAmt numeric(18,2) ,                                      
CostPrice numeric(18,4),                                
CustGroupName varchar(100), TaxAmount numeric (18,2),                                    
age int                                
)                        
Create Table #tmpSettlements                                       
(customerid int,                                       
ReceiptNo varchar(50),                                      
companyid int,                                       
invoiceid int,                                       
shopid int,                                       
settleddate datetime,                                       
departmentid int,                                       
settledamt numeric(18,2),                                      
Type varchar(50))                       
-- Commented (RefNo-1)                
-- select * into #tempvwInvoices from vwInvoices                        
-- select * into #tempvwsettlements from vwsettlements                       
 if @strCatName<>''                        
 begin                              
  set @strCatCond = ' CustomerCategory = ''' + @strCatName + ''' And '                                
 end                                 
 if @strGroupName<>''                       
 begin                               
  set @strGroupCond = ' CustGroupName = ''' + @strGroupName + ''' And '                                
 end                                 
                                 
 if @intShopID > 0                                 
 Begin                                
  set @strShop=' And  #tmpInvoices.shopid = ' + cast(@intShopID As varchar)                                
 end                                 
 if @intcustid<>''    --hari given to handle with out customerid also                                      
 Begin                                      
  set @SettleCustId = ' customerid in (' + @intcustid + ') and'                                        
  set @Invcustid = 'vwInvoices.customerid in (' + @intcustid + ') and'                                            
 End                        
                      
-- if @dtstartdate =''                                      
-- Begin                                      
--    if @intdepartid >0                                      
--    set @strquery ='insert #tmpInvoices                                      
--     Select *,0 from #tempvwInvoices vwInvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                      
--     ' invoicedate <=''' + @dtinvdate + '''' +                                       
--     ' and departmentid = ' + cast(@intdepartid as varchar)                                       
--    else                                      
--     set @strquery ='insert #tmpInvoices                                      
--     Select *,0 from #tempvwInvoices vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                       
--     ' invoicedate <=''' + @dtinvdate + ''''                      
--    End                          
-- Else                                      
-- Begin                                       
--  if @intdepartid >0                                      
--     set @strquery ='insert #tmpInvoices                                      
--     Select *,0 from #tempvwInvoices vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                       
--     ' invoicedate <=''' + @dtinvdate + '''' +                                       
--     ' and departmentid = ' + cast(@intdepartid as varchar) +                                       
--     ' and invoicedate >=''' + @dtstartdate + ''''                                      
--  else                                      
--   set @strquery ='insert #tmpInvoices                                      
--   Select *,0 from #tempvwInvoices vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                       
--      ' invoicedate <=''' + @dtinvdate + '' +                                       
--   ''' and invoicedate >=''' + @dtstartdate + ''''                                      
-- End                               
                
-- Instead of selecting from #tempvwInvoices,                 
-- required rows are fetched direcly from vwInvoices applying condition.                
-- Thus increasing speed. Old code commented above. (RefNo-1)                 
 if @dtstartdate =''                                      
 Begin                                      
    if @intdepartid >0   
    --RefNo:02                                   
    set @strquery ='insert #tmpInvoices                                      
     Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,Referenceno,remarks,InvAmt,Due,
     Type,Debtortype,updatetime,CustomerCategory,duedate,depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,
     CostPrice,CustGroupName,TaxAmount,0 from vwInvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                
     ' invoicedate <=''' + @dtinvdate + '''' +                                       
     ' and departmentid = ' + cast(@intdepartid as varchar)                                       
    else   
    --   RefNo:02                                
     set @strquery ='insert #tmpInvoices                                      
     Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,Referenceno,remarks,InvAmt,Due,
     Type,Debtortype,updatetime,CustomerCategory,duedate,depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,
     CostPrice,CustGroupName,TaxAmount ,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                       
     ' invoicedate <=''' + @dtinvdate + ''''                                      
    End                          
 Else                                      
 Begin  
                                        
  if @intdepartid >0     
                            
     set @strquery ='insert #tmpInvoices                                      
     Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,Referenceno,remarks,InvAmt,Due,
     Type,Debtortype,updatetime,CustomerCategory,duedate,depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,
     CostPrice,CustGroupName,TaxAmount ,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                       
     ' invoicedate <=''' + @dtinvdate + '''' +                                       
     ' and departmentid = ' + cast(@intdepartid as varchar) +                                       
     ' and invoicedate >=''' + @dtstartdate + '''' 
                                             
  else                                      
   set @strquery ='insert #tmpInvoices                                      
   Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,Referenceno,remarks,InvAmt,Due,
   Type,Debtortype,updatetime,CustomerCategory,duedate,depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,
   CostPrice,CustGroupName,TaxAmount ,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +                                       
      ' invoicedate <=''' + @dtinvdate + '' +                                       
   ''' and invoicedate >=''' + @dtstartdate + ''''                                      
 End                                      
              
 exec sp_Executesql @strquery                      
                      
--  if @dtstartdate =''                            
--  Begin                                      
--  if @intdepartid >0                                      
--   set @strquery  = ' insert #tmpSettlements Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +                                       
--   ' departmentid = ' + cast(@intdepartid as varchar) +                                       
--   ' and settleddate <=''' + @dtinvdate +  ''''                                       
--  else                                      
--   set @strquery  = 'insert #tmpSettlements  Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +                                       
--      ' settleddate <=''' + @dtinvdate + ''''                                        
--                                      
--  End                          
--    Else                                      
--    Begin                                       
--  if @intdepartid >0                                      
--   set @strquery  = ' insert #tmpSettlements Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +                                       
--      ' departmentid = ' + cast(@intdepartid as varchar) +                                       
--   ' and settleddate <=''' + @dtinvdate +  '' +                                       
--   ''' and settleddate >=''' + @dtstartdate + ''''                                      
--   else                                      
--   set @strquery  = 'insert #tmpSettlements  Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +                                       
--      ' settleddate <=''' + @dtinvdate + '' +                                       
--   ''' and settleddate >=''' + @dtstartdate + ''''                                      
--                                      
--   End                      
                
-- Instead of selecting from #tempvwsettlements,                 
-- required rows are fetched direcly from vwsettlements applying condition.                
-- Thus increasing speed. Old code commented above. (RefNo-1)                 
  if @dtstartdate =''                                      
  Begin                                      
  if @intdepartid >0  
  --RefNo:02                                    
   set @strquery  = ' insert #tmpSettlements Select customerid,ReceiptNo,companyid,invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where ' + @SettleCustId +                                       
   ' departmentid = ' + cast(@intdepartid as varchar) +                                       
   ' and settleddate <=''' + @dtinvdate +  ''''                                       
  else                             set @strquery  = 'insert #tmpSettlements  Select customerid,ReceiptNo,companyid,invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where ' + @SettleCustId +                                       
      ' settleddate <=''' + @dtinvdate + ''''                                        
                                      
  End                          
    Else                                      
    Begin                                       
  if @intdepartid >0                                      
   set @strquery  = ' insert #tmpSettlements Select customerid,ReceiptNo,companyid,invoiceid,shopid,settleddate,
   departmentid,settledamt,Type from vwsettlements where ' + @SettleCustId +                                       
      ' departmentid = ' + cast(@intdepartid as varchar) +                                       
   ' and settleddate <=''' + @dtinvdate +  '' +                                       
   ''' and settleddate >=''' + @dtstartdate + ''''                                      
   else        
   --   RefNo:02                        
   set @strquery  = 'insert #tmpSettlements  Select customerid,ReceiptNo,companyid,invoiceid,shopid,settleddate,
   departmentid,settledamt,Type from vwsettlements where ' + @SettleCustId +                                       
      ' settleddate <=''' + @dtinvdate + '' +                                       
   ''' and settleddate >=''' + @dtstartdate + ''''                                      
                                      
   End                            
  exec sp_Executesql @strquery                        
                       
-----RefNo:01            
 set @strquery = 'SELECT  max(invamt) invamt,isnull(sum(settledamt),0) settleamt,#tmpInvoices.invoiceid,                                      
    #tmpInvoices.customerid,#tmpInvoices.shopid,#tmpInvoices.due,#tmpInvoices.invoicedate ,                                      
    #tmpInvoices.invoiceno,#tmpInvoices.type,remarks,customername,currencyname,symbol, #tmpInvoices.duedate,       
    datediff(dd,#tmpInvoices.duedate, ''' + @dtinvdate + ''' ) overduedays, address1, address2, address3,                                       
    #tmpInvoices.referenceno,debtoraccid,b.accountdesc, aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID FROM                                       
       #tmpInvoices #tmpInvoices LEFT OUTER JOIN #tmpSettlements                                        
    vwsettlements ON #tmpInvoices.customerid = vwsettlements.customerid AND                                      
       #tmpInvoices.CompanyID = vwsettlements.companyid AND                                      
       #tmpInvoices.InvoiceID = vwsettlements.invoiceid AND                                      
       #tmpInvoices.type = vwsettlements.type AND                                      
       #tmpInvoices.shopid = vwsettlements.shopid  and                                       
   (vwsettlements.settleddate<=''' + @dtinvdate +                                      
  ''' or vwsettlements.settleddate is null),                                       
   aCurrencyMaster ,  aCustomerMaster, aAccountMaster b                                       
   WHERE #tmpInvoices.customerid = aCustomerMaster.CustomerID AND                                      
       #tmpInvoices.CompanyID = aCustomerMaster.CompanyID and                                       
   aCustomerMaster.CurrencyID = aCurrencyMaster.CurrencyID AND                                      
       aCustomerMaster.CompanyID = aCurrencyMaster.CompanyID and                                       
   aCustomerMaster.debtorAccID = b.AccountID ' + @strShop  + '                                     
   and  #tmpInvoices.invoicedate<=''' + @dtinvdate + '''                                         
   group by #tmpInvoices.invoiceid,#tmpInvoices.departmentid,                                       
   #tmpInvoices.customerid, #tmpInvoices.shopid,due ,invoicedate,                                       
   invoiceno,#tmpInvoices.type,remarks,                    
   customername,currencyname,symbol, #tmpInvoices.duedate,                                       
address1, address2, address3, #tmpInvoices.referenceno,                                      
   debtoraccid,b.AccountDesc ,aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID                                      
   having max(invamt) <> sum(isnull(settledamt,0))'                         
                      
  if @intageTodate=1                                       
  begin                                      
   update #tmpInvoices set age=datediff(day,invoicedate,CONVERT(DATETIME, @dtinvdate,102))                                       
   update #tmpInvoices set due =                                      
   case when (age  >=0 and age <= 30) then '0 - 30'                                       
  when (age  >=31 and age <= 60)  then '31 - 60'                                        
   when (age  >=61 and age <= 90) then '61 - 90'                                      
   when (age  >=91) then ' > 90' else '' end                                       
   end                                              
exec sp_Executesql @strquery                         
--select * from #tempvwsettlements                      
                      
-- Commented (RefNo-1)                
-- drop table #tempvwInvoices                      
-- drop table #tempvwsettlements                      
drop table #tmpInvoices                      
drop table #tmpSettlements                      
                      
end
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spCreditController]    Script Date: 08/25/2012 17:53:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCreditController]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCreditController]
GO

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spCreditController]    Script Date: 08/25/2012 17:53:28 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*                        
=======================================================================================================================================                        
CREATED BY   : BENZIGAR SD                        
VERIFIED BY      : PRASANTH JOSEPH                        
CREATED FOR   : 1.AUTOMATIC CLACULATION FOR FINE AGAINST THE INVOICE. TAKING INVOCIE BY USEING SPDEBTORAGESUM PROCEDURE                        
       AND CALCULATED THE OVERDUE INVOCIES. FIND THE OVER DUE DAYS AND CLACULATE FINE. FINE AMOUNT AND PERIOD WILL                        
       SET IN THE MASTER TABLE.                         
       2.FINE WILL ACCUMATE IF THE CUSTOMER NOT SETTLE THE INVOICE AMOUNT.                        
       3.CALCULATED FINE WILL CONSIDER AS INVOCIE                        
       4. SHOULD NOT CONSIDER FINE FOR THE FINE INVOICE.                        
CRETAED ON       : 26-02-2010                        
MODIFIED BY      :                         
MODIFIED BY      :                        
USAGE            :EXEC SPCREDITCONTROLLER          
Modified By : NIDHEESH P V        
COMMENTS : TAKEN THE FINE AMOUNT IN THE WHILE LOOP         
Modified By : SREEJITH G A    
Modified On : 17-04-2010    
COMMENTS : 1)FINE CALCULATION BASED ON PERCENTAGE OF INVOICE AMOUNT IS DONE    
     2)FINE CALCULATION ONCE IN A FIXED DAYS IS DONE. i.e; FINE CALCULATION ONCE IN AN INTERVAL            
     3)HANDLED CORRECT UPDATION OF FINE CALCULATED DATES AND AMOUNTS IN HEADER AND DETAILS TABLE EVEN IF THE SYSTEM STOPS WORKING FOR SOME DAYS.    
    STARTS UPDATING ONCE THE MACHINE RESUMES WORKING.    
=======================================================================================================================================                        
*/                        
-----------------------------------------------------------------------------  
--RefNo:01 
--Modified By : MANU
--Modified On : 25/08/2012  
--Purpose     : To add SalesPersonName in spdebtoragesum to show in the Outstanding Invoice report 
--------------------------------------------------------------------------                       
CREATE PROCEDURE [dbo].[spCreditController]                            
    --(                            
  ---@CompanyID  INT,                            
  --@DepartmentID INT,                            
 -- @dtasonDate  NVARCHAR(12)                            
  --  )                     
AS             
SET NOCOUNT ON                           
BEGIN     
  DECLARE @FINEENABLED AS INT    
  SELECT @FINEENABLED = FINEENABLED FROM APACKAGESETTINGS  
  IF @FINEENABLED=1   
  BEGIN  
  CREATE TABLE #debtorAgesum                            
  (                            
    invamt NUMERIC(18,2),                            
    settleamt NUMERIC(18,2),                            
    invoiceid INT,                            
    CustomerID INT,                            
    Shopid INT,                            
    due VARCHAR(30),                            
    invoicedate DATETIME,                            
    invoiceno VARCHAR(100),                            
    trtype VARCHAR(30),                            
    Remarks VARCHAR(300),                            
    Customername VARCHAR(150),                            
    Currency VARCHAR(30),                            
    Symbol VARCHAR(50),                      
    CurrencyId INT,                          
    DueDate DATETIME,                            
    overduedays INT,                            
    Address1 VARCHAR(200),                            
    Address2 VARCHAR(200),                            
    Address3 VARCHAR(200),                            
    Referenceno VARCHAR(100),                            
    DebtorAccountID INT,                            
    AccountDesc VARCHAR(100),                            
    CustomerCategory VARCHAR(80),
    SalesPerson VARCHAR(50) --<<RefNo:01>>                         
  )                            
  CREATE TABLE #Departments                        
  (                         
   departmentId int                        
  )                        
  DECLARE @CustomerID AS INT                            
  DECLARE @InvoiceID AS INT,                     
     @CompanyID AS INT,                    
     @dtasonDate AS DATETIME,                         
     @InvocieNo AS VARCHAR(25),        
     @DuePeriod AS INT,                            
     @DueDate AS DATETIME,                            
     @type AS VARCHAR(10),                            
     @NextFineID AS INT,                          
     @FineNo AS VARCHAR(40),                           
     @FineAmount AS NUMERIC(18,2),                            
     @FineID AS INT,                            
     @FineDetailID AS INT,                            
     @FineBalanceAmount AS NUMERIC(18,2),                            
     @InvAmount AS NUMERIC(18,2),                            
     @SettlementAmount AS NUMERIC(18,2),                            
     @FineCurrencyID AS INT,                            
     @RespCurrencyID AS INT,                            
     @DepCurrencyID AS INT,                            
     @ComCurrencyID AS INT,                  
     @DepartmentExchangeRate AS NUMERIC(18,2),                            
     @CompExchangeRate AS NUMERIC(18,2),                            
     @RespExchangeRate AS NUMERIC(18,2),                        
  @LastFineCalDate as datetime,                        
 -- @FineAmount AS NUMERIC(18,2),                        
  @DEPARTMENTIDS AS NVARCHAR(50),                        
  @DepartmentID AS INT,                        
  @FineAccountableDate AS DATETIME,      
  @FineCalMethod AS VARCHAR(2),    
  @FineCalPeriod AS INT    
  --------------Finding Currencies and Exchange Rates--------------------------                            
  --Teperory purpose set the Fine Currency ID Passes                     
  SET @CompanyID=1                    
  --SELECT @dtasonDate=getdate()               
  SELECT @dtasonDate= CONVERT(DATETIME,CONVERT(VARCHAR,GETDATE(),112))                             
  SELECT @FineCurrencyID=CurrencyID FROM aAccountmaster INNER JOIN aFineSetting ON AccountID=FineAccountID                        
  SELECT @FineAccountableDate=AccotableDate FROM  aFineSetting       
  SELECT @FineCalPeriod=FineCalculatingPeriod FROM aFineSetting      
  SELECT @FineCalMethod =FineCalculationMethod from aFineSetting                
  --SELECT @FineAmount=FineAmount FROM aFineSetting                         
  SELECT @ComCurrencyID=CurrencyID FROM AcompanyMaster WHERE companyID=@CompanyID                            
  SELECT @DEPARTMENTIDS=Departments,@FINEAMOUNT=FineAmount from aFineSetting                           
  EXEC spGetExchangeRate @CompanyID,@FineCurrencyID,@ComCurrencyID,@CompExchangeRate OUTPUT                        
  ----------------------------------------------------------------------------------                            
  INSERT INTO #Departments SELECT * FROM  fnSplit(@DEPARTMENTIDS,',')                        
  WHILE  (SELECT COUNT(*) FROM  #Departments)<>0                                 
  BEGIN                         
        --------------DEPARTMENTWISE CURRENCY-------------------                        
  --drop table ##TempChek                      
  SELECT @DepartmentID=MAX(DepartmentID) FROM #Departments                        
  SELECT @DepCurrencyID=depcurrencyid FROM adepartmentMAster WHERE DepartmentID=@DepartmentID                          
  EXEC spGetExchangeRate @CompanyID,@FineCurrencyID,@DepCurrencyID,@DepartmentExchangeRate OUTPUT                         
  ----------------------------------------------------------                              
    --INSERTING OUTSTANDING INVOICE DETAILS TO TEMP TABLE                            
    INSERT INTO #debtorAgesum EXEC  spDebtorAgeSum '',@dtasonDate,'',@DepartmentID,0,0,'',''                         
    delete from #debtorAgesum where invoicedate<convert(varchar,@FineAccountableDate,112)                       
    delete from #debtorAgesum where trtype='FINE'                      
   -- select * into ##TempChek from #debtorAgesum                      
    WHILE (SELECT COUNT(*) FROM #debtorAgesum)<>0                            
    BEGIN     
                        
 --drop table ##TempChek                         
 --select * into ##TempChek from #debtorAgesum                      
     --SELECTING THE ONE RECORD FOR OPERATION(FINE CALCULATION)                            
       SELECT TOP 1 @CustomerID=CustomerID,@InvoiceID=InvoiceID,@InvocieNo=invoiceno,@DueDate=DueDate,@type=trtype,@InvAmount=invamt,@SettlementAmount=settleamt                            
       FROM #debtorAgesum WHERE trtype<>'FINE' --AND invoicedate>=convert(varchar,@FineAccountableDate,112) --and Shopid in (SELECT SHOPID FROM ashops WHERE departmentID=@DepartmentID)                        
       GROUP BY CustomerID,InvoiceID,DueDate,trtype,settleamt,invamt,invoiceno                            
       SET @LastFineCalDate=NULL    
       SELECT  @LastFineCalDate=fhLastFineCalDate FROM  aFineHeader  WHERE fhCustomerID=@CustomerID and fhInvoiceID=@InvoiceID and fhTransactionType=@type                            
                             
     IF @InvoiceID<>'' OR @InvoiceID IS NOT NULL                        
     Begin                        
       --CHECKING DUE DATE IS LESS THAN THAN SYSTEM DATE, THEN ONLY NEED TO CALCULATE FINE                            
       IF @DueDate< @dtasonDate and @InvAmount>@SettlementAmount AND @dtasonDate > ISNULL(@LastFineCalDate,'19000101')                        
       BEGIN                            
          --CHECKING ALREADY FINE CALCULATED INVOICE OR NOT                            
           IF (SELECT COUNT(*) FROM  aFineHeader WHERE fhCustomerID=@CustomerID and fhInvoiceID=@InvoiceID and fhTransactionType=@type) =0                            
           BEGIN                         
            --------------------------------FINDING INVOICE NO-----------------------                          
    set  @FineNo=@InvocieNo+'/FINE'                        
             -------------------------------ECHANGE RATE FINDING------------------------------                            
             --FINDING RESPECTIVE CURRENCYID FOR CUSTOMER,COMPANY AND DEPARTMENT                            
             SELECT @RespCurrencyID=CurrencyID FROM acustomermaster WHERE CustomerID=@CustomerID                            
               -- set @RespExchangeRate= EXEC spGetExchangeRate @CompanyID,@FineCurrencyID,@RespCurrencyID                            
             EXEC spGetExchangeRate @CompanyID,@FineCurrencyID,@RespCurrencyID,@RespExchangeRate OUTPUT                            
             ----------------FINDING FINE AMOUNT-------------       
   IF @FineCalMethod='A'                
    BEGIN    
     SELECT @FineAmount=FineAmount FROM aFineSetting      
    END    
   ELSE IF @FineCalMethod='P'    
    BEGIN    
     SELECT @FineAmount=(FinePercentage*(@InvAmount-@SettlementAmount))/100 FROM aFineSetting      
    END    
   ---CALCULATING THE DUE PERIOD FOR FIRST INSERTION    
   SELECT @DuePeriod=DATEDIFF(day,@DueDate,CONVERT(DATETIME, getdate(),102))    
   IF @DuePeriod>=@FineCalPeriod    
   BEGIN    
    ---TO START FINE CALCULATION AFTER FIRST FINE CALCULATION(FIRST FINE WILL BE CALCULATED FROM THE DUEDATE+CALCULATING PREIOD)     
    SET @LastFineCalDate=DATEADD(DAY,@FineCalPeriod,@DueDate)    
    ---FIND THE MAXIMUM FINEID FROM AFINEHEADER    
    SELECT @NextFineID=CASE ISNULL(MAX(fhFineID),0) WHEN 0 THEN 1 ELSE MAX(fhFineID)+1 END   FROM aFineHeader                             
    --INSERT INTO FINE HEADER               
    INSERT INTO aFineHeader SELECT @CompanyID,@DepartmentID,Shopid,1,@NextFineID,@FineNo,trtype,invoiceid,invoiceno,                            
    invoicedate,CustomerID,DueDate,@LastFineCalDate,@RespExchangeRate,@DepartmentExchangeRate,@CompExchangeRate,0                            
    FROM #debtorAgesum WHERE CustomerID=@CustomerID and InvoiceID=@InvoiceID                            
    --INSERT INTO FINE DETAILS      
    INSERT INTO aFineDetail VALUES(@NextFineID,1,@LastFineCalDate,@FineAmount,0)     
    --FINDING DUE PERIOD (BETWEEN LAST CALCULATED AND CURRENT DATE) AFTER FIRST INSERTION                           
    SELECT @DuePeriod=DATEDIFF(day,@LastFineCalDate,CONVERT(DATETIME, getdate(),102))      
    --FINDING THE INTERVAL FOR WHICH THE FINE HAS TO BE CALCULATED (BELOW CHECKING IS DONE TO ENSURE RELIABILITY IF IN CASE THERE IS ANY SERVER DOWN)    
    IF  @DuePeriod>=@FineCalPeriod    
      BEGIN    
       WHILE (@LastFineCalDate<=@dtasonDate)    
        BEGIN    
         SET @LastFineCalDate=DATEADD(DAY,@FineCalPeriod,@LastFineCalDate)     
         IF @LastFineCalDate<=@dtasonDate---TO ENSURE IF THE LAST CALCULATED DATE EXCEED THE CURRENT DATE    
         BEGIN    
          --FINDING THE NEXT DETAILID     
          SELECT @FineDetailID=COUNT(*)+1 FROM aFineDetail WHERE fdFineID=@NextFineID     
          --UPDATE THE LAST FINE CALCULATED DATE TO THE HEADER                            
          UPDATE aFineHeader SET fhLastFineCalDate=@LastFineCalDate WHERE fhFineID=@NextFineID     
          --INSERT INTO FINE DETAILS      
          INSERT INTO aFineDetail VALUES(@NextFineID,@FineDetailID,@LastFineCalDate,@FineAmount,0)             
         END    
        END    
      END     
    SET @LastFineCalDate=NULL     
   END    
            
           END                            
        ELSE                            
           BEGIN                            
             --FINDING THE FINEID FROM THE FINEHEADER                            
             SELECT @FineID=fhFineID FROM  aFineHeader WHERE fhCustomerID=@CustomerID and fhInvoiceID=@InvoiceID and fhTransactionType=@type                            
    SELECT @DuePeriod=DATEDIFF(day,@LastFineCalDate,CONVERT(DATETIME, getdate(),102))                       
             -----SELECT  @FineBalanceAmount=@FineAmount-SUM(fdFineAmount) FROM aFineDetail WHERE fdFineID=@FineID            
     ----TO FIND THE FINE AMOUNT    
     IF @FineCalMethod='A'                
     BEGIN    
      SELECT @FineAmount=FineAmount FROM aFineSetting      
     END    
     ELSE IF @FineCalMethod='P'    
     BEGIN    
      SELECT @FineAmount=(FinePercentage*(@InvAmount-@SettlementAmount))/100 FROM aFineSetting      
     END    
--     SET  @FineBalanceAmount=@DuePeriod*@FineAmount     
     SET  @FineBalanceAmount=@FineAmount     
      --FINDING THE INTERVAL FOR WHICH THE FINE HAS TO BE CALCULATED (BELOW CHECKING IS DONE TO ENSURE RELIABILITY IF IN CASE THERE IS ANY SERVER DOWN)    
     SELECT @FineCalPeriod=FineCalculatingPeriod FROM aFineSetting    
     IF @DuePeriod>=@FineCalPeriod    
     BEGIN    
      WHILE (@LastFineCalDate<=@dtasonDate)    
       BEGIN    
        SET @LastFineCalDate=DATEADD(DAY,@FineCalPeriod,@LastFineCalDate)     
        IF @LastFineCalDate<=@dtasonDate---TO ENSURE IF THE LAST CALCULATED DATE EXCEED THE CURRENT DATE    
        BEGIN    
         --FINDING THE NEXT DETAILID     
         SELECT @FineDetailID=COUNT(*)+1 FROM aFineDetail WHERE fdFineID=@FineID     
         --UPDATE THE LAST FINE CALCULATED DATE TO THE HEADER                            
         UPDATE aFineHeader SET fhLastFineCalDate=@LastFineCalDate WHERE fhFineID=@FineID     
         --INSERT INTO FINE DETAILS      
         INSERT INTO aFineDetail VALUES(@FineID,@FineDetailID,@LastFineCalDate,@FineAmount,0)             
        END    
       END    
      SET @LastFineCalDate=NULL    
     END      
           END                            
        END                          
                            
          DELETE FROM #debtorAgesum WHERE  CustomerID=@CustomerID AND InvoiceID=@InvoiceID and trtype=@type                           
  END                          
   END                           
  DELETE FROM #debtorAgesum                        
  DELETE FROM   #Departments WHERE departmentID=@DepartmentID                        
 END                      
END  
END     
GO

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

/****** Object:  StoredProcedure [dbo].[spCreditForOverdueCustomers]    Script Date: 08/25/2012 17:38:30 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCreditForOverdueCustomers]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCreditForOverdueCustomers]
GO

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spCreditForOverdueCustomers]    Script Date: 08/25/2012 17:38:30 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--spCreditForOverdueCustomers 1,25,'S',2,'20110402',529.96,0              
---spCreditForOverdueCustomers 1,9729,'D',1,'20101127',100        
---spCreditForOverdueCustomers 1,9729,'s',4,'20101127',3.5,0                    
------------------------------------------------------------                          
-- Created by : Nidheesh P V                         
-- Created on : 24-03-2011                          
-- Comments : To check any invoice is over due for this customer.          
-- MODIFIED BY MANU ON 01/06/2011 TO INCREASE THE SIZE OF ADDRESS COLUMN IN THE TABLE VARIABLE   
-- @tempDebtorage FOR THE BUGFIXING OF THE TICKET: OIE-638002     
-----------------------------------------------------------------------------  
--RefNo:1
--Modified By : MANU
--Modified On : 25/08/2012  
--Purpose     : To add SalesPersonName in spdebtoragesum to show in the Outstanding Invoice report 
--------------------------------------------------------------------------         
------------------------------------------------------------                      
CREATE PROC [dbo].[spCreditForOverdueCustomers]                               
 @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,@NoCreditForOverdueCustomer as bit=0 output,                
 @StrMessage as varchar(100)='' output,@numDebitbalanceOut  as numeric(18,2)=0 output                              
as                    
  Declare @numDebitBal as numeric (18,2),@intdue as int,                       
 @NoCreditForOverdueCustomers as int,@dtintdatecon as varchar(10),                          
 @intCustomerIDcon as varchar(1000), @dtInvMinDate as datetime ,@dtDuedate as datetime,                      
 @intDept as int,@chCreditLimitType as char(1)               
              
  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(250), address2 varchar(250),   
 address3 varchar(250),referenceno varchar (100),debtoraccid int,accountdesc varchar(100),  
 CustomerCategory varchar(100),CurrencyID int
 ,SalesPerson VARCHAR(50) --<<RefNo:01>> 
 )                                
                         
begin         
  SET NOCOUNT ON          
  SET @numDebitBal  = 0                              
  SET @intdue=0                            
  SET @NoCreditForOverdueCustomers = 0           
  SET @numDebitbalanceOut=0         
  SET @numDebitBal = 0          
            
  ----------------               
  --here checking  pending invoice against the customer( having settings in package settings)                                 
  select @NoCreditForOverdueCustomers =isnull(NoCreditForOverdueCustomers,0) from apackagesettings                              
  ----------------         
  -- Get customer Due period                           
  if @CheckMode='S'         
  begin        
 --If shop invoice is selected the it checks the due period given in that shop        
 SELECT @intdue=DuePeriod FROM aShopCustomerDetails                               
 WHERE ShopID = @intLocationID and customerID = @intCustomerID          
 end        
  else        
 --If hq invoice is selected the it checks the due period given in hq(customer master)        
  begin        
 SELECT @intdue=Dueperiod  from aCustomerMaster where CustomerID = @intCustomerID         
  end        
  ----------------          
  -- Get credit limit type and override the parameter                          
  -- (S-Shopwise, D-Deptwise, C-Companywise)                         
  select @chCreditLimitType=isnull(CreditLimitType,'S') from aPackageSettings           
  ----------------        
          
  --If credit limit level is shop 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         
                           
  -- **** METHOD 1: SHOP-WISE ****                              
  if @chCreditLimitType='S' and @CheckMode='S'         
   --If shop credit limit level is set and shop invoice is selected then this will executed.                                                 
 begin                
   INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,0,0,@intlocationid,'',''--shopwise                
      SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0),@dtInvMinDate=MIN(invoicedate) FROM @tempDebtorage                
   ------SELECT @numDebitbal,@dtInvMinDate              
 end                  
                                             
 -- **** METHOD 2: DEPARTMENT-WISE ****                          
 --If Department credit limit level is set then this will executed.                             
  if @chCreditLimitType='D'                          
 begin                 
  SELECT @intDept=DepartmentID from ashops where ShopID=@intlocationid                
  INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,@intDept,0,0,'',''--Deptwise                
  SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0),@dtInvMinDate=MIN(invoicedate) FROM @tempDebtorage                
  -----SELECT @numDebitbal,@dtInvMinDate              
 end                  
                                  
 -- **** METHOD 3: COMPANY-WISE ****                          
 -- Else, check if credit exceeds COMPANY-WISE credit limit.                                       
  if @chCreditLimitType='C'                             
 begin                  
  INSERT INTO @tempDebtorage EXEC spdebtoragesum '',@dtInvDate,@intcustomerid,0,0,0,'',''--Comwise                
  SELECT @numDebitbal=ISNULL(SUM(ISNULL(invamt,0)-ISNULL(settleamt,0)),0),@dtInvMinDate=MIN(invoicedate) FROM @tempDebtorage                
  -----SELECT @numDebitbal,@dtInvMinDate              
 end           
 ------------------        
  SET @numDebitbalanceOut=@numDebitbal         
  SET @dtDuedate = dateadd(d,@intdue,@dtInvMinDate)                                           
------------------------------------------------              
  if (@numDebitbal-@ExcludeInvAmt)>0 and @dtInvDate>@dtDuedate and @dtInvMinDate is not null                    
 begin                    
  set @NoCreditForOverdueCustomers=1                    
 end                    
  else                    
 begin                    
  set @NoCreditForOverdueCustomers=0                    
 end                    
-----------------                    
  if @NoCreditForOverdueCustomers=1                     
 begin                    
  set @StrMessage='No credit for overdue customers.An invoice of this Customer is overdue.'                    
  --SELECT @NoCreditForOverdueCustomers ---No Credit For Overdue Customer               
  --SELECT @StrMessage               
  RETURN @NoCreditForOverdueCustomers ---No Credit For Overdue Customer          
  RETURN @StrMessage               
  RETURN @numDebitbalanceOut            
 end                    
  else                  
 begin               
  set @StrMessage=''                       
  --SELECT 0              
  --SELECT ''              
  RETURN @NoCreditForOverdueCustomers ---Credit For Overdue Customer             
  RETURN @StrMessage           
  RETURN @numDebitbalanceOut             
 end                    
-----------------         
  SET NOCOUNT OFF                        
end 
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spCustomerCreditLimitExceeds]    Script Date: 08/25/2012 17:40:08 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCustomerCreditLimitExceeds]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spCustomerCreditLimitExceeds]
GO

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spCustomerCreditLimitExceeds]    Script Date: 08/25/2012 17:40:08 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
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).      
------------------------------------------------------------                  
                    
------------------------------------------------------------                                
--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)

-----------------------------------------------------------------------------  
--RefNo:7
--Modified By : MANU
--Modified On : 25/08/2012  
--Purpose     : To add SalesPersonName in spdebtoragesum to show in the Outstanding Invoice report 
-------------------------------------------------------------------------- 
--spCustomerCreditLimitExceeds 1,2,'',1,'',0,0
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
,SalesPerson VARCHAR(50)) --<<RefNo:07>>                                              
 ------------------------------------------------------                                           
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:
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

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

--Created By  : Aneesh              
--Created On  : 14-09-2006              
--Purpose     : To update details to the POS Header Table [losPosheader]            
--Modified BY : Shinu        
--Modifies On : 15-03-2007,20-11-2007       
--Purpose : To insert Discount amount In LOSPOSHEADER       
--    : To Insert Delivery note Bit       
--Last Modified By:MANUNADH.U 18-03-2011    
---------------------------------------------------------------------------------------------
--Upgrade By : Bijesh. B
--Date		 : 07/06/2011
--Purpose	 : adding chequeid column and post date cheque Column(Upgrading PD Cheque
--	           feature from Sonee)
---------------------------------------------------------------------------------------------
--Upgrade By : Bijesh. B
--Date		 : 27/12/2011
--Purpose    : Need Tin for Cash customer
--Desc       : @CustomerTIN column added
--Ticket id  : BLE-583962 (Sonee)  
---------------------------------------------------------------------------------------------
--RefNo-1
--Upgrade By : Bijesh. B
--Date		 : 04/09/2012
--Purpose    : While taking company wise Daily sales Gst separated reports, wrong amount is showing
--Ticket id  : WEZ-940061 (SIMDI-GST separated report-Defect Sheet)  
---------------------------------------------------------------------------------------------

create PROC spUpdatePOSHeader  
 @intBillId As Int ,                  
 @intShopId As Int,                   
 @intCounterId As Int,                  
 @intUserId As Int,                  
 @intSalesPerId As Int,                  
 @dtBillDate As DateTime,                  
 @strCustName As Varchar(100),                  
 @strExRate As Varchar(30),                  
 @intDepExRate As  Numeric(18,9), --RefNo-1 changed Numeric(18,2) to Numeric(18,9)                  
 @intDiscount As  Numeric(18,2),                  
 @intBillAmt As  Numeric(18,2),                  
 @intCashAccId As Int,                  
 @intCustId As Int,                  
 @strRemarks As Varchar(250),                  
 @intCmpExRate As  Numeric(18,9),  --RefNo-1 changed Numeric(18,2) to Numeric(18,9)
 @intDiscountAmt As  Numeric(18,2) ,        
 @intDeliveryNeeded  as Int=0,  
 @intChequeId As Int,      
 @PostdateChk as bit,
 @CustomerTIN as varchar(50)=''                 
As                  
Begin                    
 Declare @intDepId As Int                
 Declare @intFinId As Int                  
 Declare @intBillNo as Int                
 Declare @strUser As Varchar(20)                  
 Declare @intSalesAccId As Int                  
 Declare @intWholeSale As Int                
 Declare @strBillNo as Varchar(20)                  
 Declare @strCardNo as Varchar(20)                   
              
 --Finding the username with the @intUserId passed                
 --Select @strUser = UserName From aUsers Where UserId=@intUserId                  
 Select @strUser = UserName From lousers Where UserId=@intUserId  -- Modified By MANUNADH  
            
 --Finding the Sales Acc Id,Wholesale bit,Department Id with the @intShopId passed                
 Select @intSalesAccId = ShopSalesaccountID,@intWholeSale = TruncateCheck,@intDepId = DepartmentId     
 From aShops Where ShopId=@intShopId                  
                
 --Getting the Customer Card Id - Uncomment the following code if you need to save it.                
 --If @intCustId>0 Select @strCardNo=CustomerCardNo From aCustomerMaster Where customerid=@intCustId                
                
 --Setting the customer id to null if no customer is selected                 
 If @intCustId=0 Set @intCustId=NULL                 
                
 --Setting the sales person id to null if no sales person is selected                 
 If @intSalesPerId=0 Set @intSalesPerId=NULL                 
            
 Update losPosHeader     
 Set poshCustomerName=@strCustName,poshCancelledRemarks=@strRemarks,poshRecModifyUser=@strUser,    
  poshDiscount=@intDiscount,poshBillAmount=@intBillAmt,poshCashAccID=@intCashAccId,poshSalesAccID=@intSalesAccId,    
  poshExchangeRate=@intCmpExRate,updatetime=GetDate(),poshsalespersonid=@intSalesPerId,    
  poshcustomerid=@intCustId,poshdepexrate=@intDepExRate,poshexchangerates=@strExRate,    
  --poshUserId=@intUserId,              
  poshModifyUserId=@intUserId,              
  poshCounterId=@intCounterId ,poshDiscountAmt=@intDiscountAmt ,poshDeliveryNeeded=@intDeliveryNeeded,     
  poshChequeAccID = @intChequeId, PosPostDate = @PostdateChk ,poshCustomerTIN= @CustomerTIN  
 Where poshBillId=@intBillId And poshShopId=@intShopId                
End      

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

GO
/****** Object:  StoredProcedure [dbo].[spCustomerSettlement]    Script Date: 05/28/2011 14:13:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spCustomerSettlement]') AND type in (N'P', N'PC'))
BEGIN
	DROP PROCEDURE spCustomerSettlement
END
GO
/****** Object:  StoredProcedure [dbo].[spCustomerSettlement]    Script Date: 05/28/2011 14:13:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 

                 
/*                              
-------------------------------------------------------------------------------------------                                      
SPName      : spCustomerSettlement                                        
Coded By    : Vinoth Murugan                                        
Date        : 16-02-2010                                        
Purpose     : To speed up Customer settlement.                             
Modified on : 17/03/2007                            
Modified By : VINOTHMURUGAN V                                       
-------------------------------------------------------------------------------------------                                
Modified On : 20-04-2010          
Modified By : Sreejith G A          
Purpose: Added the condition of fhinvoicecancelled = 0       
     and fhshopid=0 in Fine portion to populate Fine Invoices generated from Acc Invoices.      
-------------------------------------------------------------------------------------------         
Modified On : 22-12-2010          
Modified By : Shine Das  
Purpose: DELETE FROM #tempid changed to TRUNCATE TABLE #tempid  
-------------------------------------------------------------------------------------------                                 
Modified On : 19-06-2012          
Modified By : Jyothish 
Purpose:  TaxAmount is Added to serviceinvoice
 
Modified On : 11-08-2012            
Modified By : Jyothish   
Purpose:  #tempid identity(1,1) is chaged 
*/                                   
create PROC spCustomerSettlement(@customerid AS INT,@departmentid AS INT,@companyid AS INT)                                               
AS                                         
DECLARE @ID  INT,@INDEX  INT,@RECCOUNT  INT,@AMT  NUMERIC(18,2),@AMT1  NUMERIC(18,2),                                            
   @dblamt NUMERIC(18,2),@billdate datetime,@billno int,                                            
   @billamt NUMERIC(18,2),@Discount NUMERIC(18,2),@shopid int ,@INVAMT NUMERIC(18,2),@product int  ,@TaxAmount NUMERIC(18,2)                                  
                                             
BEGIN                                             
                                        
CREATE TABLE #temp (Location varchar(50),InvoiceNo varchar(50),InvoiceDate  datetime,                                              
InvoiceAmount numeric(18,2),SettleAmount numeric(18,2),InvoiceID int,InvoiceType  varchar(20),                                              
ShopID int)                                    
                                    
create table #tempid(id int identity(1,1),InvoiceID int,Product int,discount NUMERIC(18,2),taxamount NUMERIC(18,2))    
                     
                      
                      
                      
----------------------------------------------------------------                      
-------------------------------------------------------------------------------                            
--Client      : SIMDI                            
--Modified on : 17/03/2010                            
--Modified By : VINOTHMURUGAN V                            
--Purpose     : Adding Fine Amount.                            
TRUNCATE TABLE  #tempid                                  
If @departmentid = 0                                     
BEGIN                                  
 INSERT INTO #TEMPID                                  
 select fhfineid, 0,'0.00','0.00' from aFineHeader                                   
 where fhcompanyid = @companyid and fhcustomerid = @customerid  and fhinvoicecancelled=0 and fhshopid=0                               
                                             
END                                  
     Else                                    
BEGIN                                  
  INSERT INTO #TEMPID                                  
     select fhfineid, 0,'0.00','0.00' from aFineHeader                                    
     where fhcompanyid = @companyid and fhcustomerid = @customerid                                  
     and fhDepartmentID = @departmentid   and fhinvoicecancelled=0 and fhshopid=0                                   
End                                   
                                   
SET @INDEX = 1                                             
SET @RECCOUNT =(SELECT COUNT(id) from #TEMPid)                             
                                              
WHILE (@INDEX <= @RECCOUNT)                                    
BEGIN                                     
                           
 SET @ID = (SELECT InvoiceID FROM #TEMPID WHERE ID= @INDEX)                                
                          
                            
 set @INVAMT =(select isnull(sum(fdfineAmount*fhRespExchangeRate),0) amount from afinedetail inner join afineheader on fdfineid=fhfineid                                     
 where   fdfineid = @ID )                             
                             
-- SET @INVAMT =(Select (@INVAMT * fhrespexchangerate) from  afineheader                             
-- where  fhcompanyid = @companyid and fhfineid = @ID)                        
                      
 set @amt=(select isnull(sum(AmountReceived),0) as amt from receiptvoucherdetails rd,                                     
 receiptvoucherheader rh where rd.companyid = rh.companyid and rh.companyid = @companyid                                    
 and rd.receiptid = rh.receiptid and rh.cancelled = 0 and rd.fineid = @ID)                           
                               
                                   
 SET @AMT1 =( SELECT isnull(sum(settlementamount),0) FROM customersettlementdetail cd, customersettlementheader ch                                   
 WHERE  ch.companyid = cd.companyid and ch.csid = cd.csid and ch.cancelled = 0                                    
 and ch.companyid = @companyid  AND cd.fineid = @ID)                          
                          
                      
--select *  FROM customersettlementdetail cd, customersettlementheader ch                            
-- WHERE  ch.companyid = cd.companyid and ch.csid = cd.csid and ch.csid=18691                      
--                                
--                                    
 INSERT INTO #TEMP                                  
 SELECT 'Head Quarters',fhfineno,fhinvoicedate,ISNULL( (@INVAMT-(@AMT1+@amt)),0),'0.00',                                  
 fhfineid,'FINE',0  from aFineHeader                                    
 where fhcompanyid = @companyid and fhcustomerid = @customerid                                  
 and fhDepartmentID = @departmentid  AND fhfineid =@ID                                
                                    
set @index = @index + 1                                   
 END                            
                         
-------------------------------------------------------------------------------                        
--------------------------------------------------------------                                    
                                    
IF @departmentid = 0                                      
begin                                    
   insert into #tempid                                    
   select InvoiceID,Product,isnull(discount,0)discount ,ISNULL(TaxAmount,0) taxamount                                   
   from accountsinvoiceheader                                     
   where Cancelled=0 and proforma = 0 and cashinvoice = 0 and companyid = @companyid                                    
   and customerid = @customerid                                    
end                                    
   Else                                    
begin                                    
   insert into #tempid                                    
   select InvoiceID,Product,isnull(discount,0)discount ,ISNULL(TaxAmount,0) taxamount                                    
   from accountsinvoiceheader                                     
   where Cancelled=0 and proforma = 0 and cashinvoice = 0 and companyid = @companyid                                    
   and customerid = @customerid and DepartmentID= @departmentid                                    
           
                                    
End                                    
                                     
SET @INDEX = 1                                
SET @RECCOUNT =(SELECT COUNT(id) from #TEMPid)                                     
                                              
WHILE (@INDEX <= @RECCOUNT)                                    
BEGIN                                       
                                    
 SET @ID = (SELECT InvoiceID FROM #TEMPID WHERE ID= @INDEX)                                    
 set @product =(SELECT Product FROM #TEMPID WHERE ID= @INDEX)                                    
 set @discount = (SELECT discount FROM #TEMPID WHERE ID= @INDEX)  
 set @TaxAmount = (SELECT TaxAmount FROM #TEMPID WHERE ID= @INDEX)  
                                
                                      
 set @INVAMT =(select isnull(sum(ServiceQty * Amount),0) prodamount from ServiceInvoiceDetails                                     
 where companyid = @companyid and @product=0 and invoiceid = @ID )                                     
                                
 set @INVAMT = (@INVAMT+@TaxAmount) - @discount                                    
                                             
 set @amt=(select isnull(sum(settlementamount),0) as amt from customersettlementdetail cd,                                     
 customersettlementheader ch where cd.companyid = @companyid and                                     
 cd.csid = ch.csid and cd.companyid = ch.companyid and cancelled = 0 and AccInvoiceID = @ID)                                    
                                             
 set @amt1=(select isnull(sum(AmountReceived),0) as amt1 from receiptvoucherdetails rd,                                     
 receiptvoucherheader rh where rd.companyid = rh.companyid and rh.companyid = @companyid                                    
 and rd.receiptid = rh.receiptid and rh.cancelled = 0 and rd.hqAccountsInvoiceID = @ID)                                   
                                
 insert into #temp                                    
 select 'Head Quarters',InvoiceNo,InvoiceDate,@INVAMT - ((@amt+@amt1 + isnull(h.discount,0))),'0.00',h.InvoiceID,                                    
 'HSERVICE',0 from accountsinvoiceheader h                                      
 where companyid = @companyid and Cancelled=0 and proforma = 0 and cashinvoice = 0                                     
 and customerid = @customerid  and (@amt+@amt1)< @INVAMT and h.invoiceid = @ID                                   
                                
 set @index = @index + 1                                    
                                               
end                                    
                                    
                                    
 ----------------------------------------------------------------                                      
TRUNCATE TABLE #tempid                                  
If @departmentid = 0                      
begin                                    
 insert into #tempid                                     
 select dcniD, 0,'0.00','0.00' from debitcreditnote                                   
 where DCNCancelled=0 and dcndebit = 1 and dcncompanyid = @companyid                                    
 and dcncustomerid = @customerid                                  
end                                  
    Else                            
begin                                  
 insert into #tempid                                    
 select dcniD, 0,'0.00','0.00' from debitcreditnote                                    
 where DCNCancelled=0 and dcndebit = 1 and dcncompanyid = @companyid                                  
 and dcndepartmentid =@departmentid                                   
 and dcncustomerid = @customerid              end                                  
                                  
SET @INDEX = 1                                             
SET @RECCOUNT =(SELECT COUNT(id) from #TEMPid)                                              
          
WHILE (@INDEX <= @RECCOUNT)                                    
BEGIN                                       
                                    
 SET @ID = (SELECT InvoiceID FROM #TEMPID WHERE ID= @INDEX)                                    
                                   
 SET @AMT = (SELECT isnull(sum(settlementamount),0) FROM customersettlementdetail cd,                                   
 customersettlementheader ch WHERE  ch.companyid = cd.companyid and                                   
 ch.csid = cd.csid and ch.cancelled = 0 and ch.companyid = @companyid AND cd.dcnid = @ID)                                   
                                
 SET @AMT1 =(SELECT isnull(sum(AmountReceived),0) FROM receiptvoucherdetails rd,                                   
 receiptvoucherheader rh WHERE rd.companyid = rh.companyid and rh.companyid = @companyid                                   
 and rd.receiptid = rh.receiptid and rh.cancelled = 0 and rd.dcnid = @ID )                                  
                                
                                
 INSERT INTO #TEMP                                  
 SELECT 'Head Quarters',dcnno,dcnDate,ISNULL((dcnAmount-(@AMT + @AMT1)),0),'0.00',dcnid,'HDEBIT',0                                  
 from debitcreditnote where DCNCancelled=0 and dcndebit = 1 and dcncompanyid = @companyid                                  
 and dcndepartmentid =@departmentid  and dcncustomerid = @customerid AND (@AMT + @AMT1) <= dcnAmount                                  
 AND dcniD = @ID                                  
                                
 set @index = @index + 1                                   
END                  
                                  
                                  
-----------------------------------------------------------------                                   
TRUNCATE TABLE  #tempid                                  
If @departmentid = 0                                     
BEGIN                                  
 INSERT INTO #TEMPID                                  
 select phpaymentID, 0,'0.00','0.00' from ahqpaymentvoucherheader                                   
 where phcancelled =0 and phcompanyid = @companyid and phcustomerid = @customerid                                    
                                             
END                                  
     Else                                    
BEGIN                                  
  INSERT INTO #TEMPID                                  
     select phpaymentID, 0,'0.00','0.00' from ahqpaymentvoucherheader                                    
     where phcancelled =0 and phcompanyid = @companyid and phcustomerid = @customerid                                  
     and phDepartmentID = @departmentid                                  
End                                   
                                   
SET @INDEX = 1                                             
SET @RECCOUNT =(SELECT COUNT(id) from #TEMPid)                  
                                              
WHILE (@INDEX <= @RECCOUNT)                                    
BEGIN                                     
                                   
 SET @ID = (SELECT InvoiceID FROM #TEMPID WHERE ID= @INDEX)                                   
                                      
 SET @AMT =(SELECT isnull(sum(AmountReceived),0) FROM receiptvoucherdetails rd, receiptvoucherheader rh                                  
 WHERE  rd.companyid = rh.companyid and rh.companyid = @companyid                                   
 and rd.receiptid = rh.receiptid and rh.cancelled = 0 and rd.phpaymentid = @ID)                                  
                                   
 SET @AMT1 =( SELECT isnull(sum(settlementamount),0) FROM customersettlementdetail cd, customersettlementheader ch                                   
 WHERE  ch.companyid = cd.companyid and ch.csid = cd.csid and ch.cancelled = 0                                    
 and ch.companyid = @companyid  AND cd.paymentid = @ID)                   
                                    
 INSERT INTO #TEMP                                  
 SELECT 'Head Quarters',phpaymentno,phPaymentDate,ISNULL( phcustomeramount- (@AMT+@AMT1),0),'0.00',                                  
 phpaymentid,'payment',0  from ahqpaymentvoucherheader                                    
 where phcancelled =0 and phcompanyid = @companyid and phcustomerid = @customerid                                  
 and phDepartmentID = @departmentid AND (@AMT+@AMT1)<= phcustomeramount  AND phpaymentID =@ID                                  
                                    
 set @index = @index + 1                                   
 END                                  
                                
insert into #temp                                           
exec SPPopulateShopInvoiceDetails_vw @customerid ,@companyid ,@departmentid                               
                                
select * from #temp where InvoiceAmount > 0                                  
Drop table #temp                                    
Drop table #tempid                                    
end    

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:TQO-404715
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


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

  
--Last Modified on  : 12/12/02  
--Modified by  : leo  
--Comments  : v3  
--last modified on  :16/06/03  
--modified by  :venki  
--comments  :added dept symbol also  
--modified by  :Prasanth Joseph  
--comments  :added HP Details  
-------------------------------------  
--MODIFIED BY: NIDHEESH PV  
--MODIFIED ON: 16/12/2010  
--COMMENTS: CHANGED THE LABEL  
--changed 'Payments Deducted' to 'Amount After Payments'  
--because 'Payments Deducted' makes a bit confusion while using the report.  
------------------------------------------------------------------------------  
-- Modified by : Bijesh.B  
-- Date        : 25/07/2011  
-- RefNo       : RefNo-1  
-- Comments    : PD Cheque feature added, corrected error in total sales  
--               Since Post Dated Cheque (Fully/Partially) option was included  --     in POS(Sonee) interface,the difference between 'BILL AMOUNT' and  --     PD Cheque Amount is the actual Cash Sales     -- spDayendReport '20110606',11  
-------------------------------------------------------------------------------  
-- Modified by : Nidheesh P V  
-- Date        : 20/10/2011  
-- RefNo       : RefNo-2  
-- Comments    : Added tax details in the day end report.  
--commented the service invocie section because service invoice is already listing in Credit Sales  
-------------------------------------------------------------------------------  
-- Modified by : Benzigar S D  
-- Date        : 28/10/2011  
-- RefNo       :  
-- Comments    : Added prefix for GrnhGoodsreturnnoteDate  
-------------------------------------------------------------------------------  

-- Modified by : Jyothish.SR
-- Date        : 11/08/2012  
-- RefNo       :  RefNo-3  
-- Comments    : Goods Retun amout postive value changed to -ve
-------------------------------------------------------------------------------  
create proc [dbo].[spDayendReport](@transdate as varchar(10), @intshopid as int) as  
declare @dttransdate as datetime  
set @dttransdate = convert(datetime,@transdate,101)  
select cs.companyid , cs.shopid, accountdesc, 'Cash' as reference, billdate,  
sum(amount) amount, sum(damount) damount, sum(camount) camount, 1 as type, accountdesc as trans,  
sum(amount) as mode, sum(damount) as dmode, sum(camount) as cmode, sum(amount) sales,  
sum(damount) dsales , sum(camount) csales ,cu.symbol  
from vwcashsales cs, aaccountmaster am,  
ashops sh,adepartmentmaster ad,acurrencymaster cu  
where cs.accountid = am.accountid and cs.companyid = am.companyid and cash=1 and  
sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
sh.shopid=cs.shopid and  
billdate=@dttransdate and cs.shopid =@intshopid  
group by cs.companyid ,cs.shopid, billdate, accountdesc ,cu.symbol  
union all  
--added to show  the labels after the groups  
select s.companyid, s.shopid , '' AS accountdesc, '' AS reference,billdate, 0.0 amount, 0.0 damount, 0.0 camount,  
2 as type, 'Total Cash Sales' as trans, 0.0 amount, 0.0 damount, 0.0 camount, 0.0 sales,  
0.0 dsales , 0.0 csales  ,cu.symbol  
from ashops s, vwcashsales  c,adepartmentmaster ad,acurrencymaster cu  
where  
s.shopid=c.shopid and s.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
billdate=@dttransdate  and s.shopid =@intshopid  
group by s.companyid, s.shopid, billdate ,cu.symbol  
--RefNo-1 start  
UNION ALL  
--FOR PD Cheque Total Amount  
select cs.companyid , cs.shopid, accountdesc, 'POS-PD CHEQUE' as reference, billdate,  
sum(amount) amount, sum(damount) damount, sum(camount) camount, 3 as type,  
'Total Post Dated Cheque Amount' as trans,  
sum(amount) as mode, sum(damount) as dmode, sum(camount) as cmode, sum(amount) sales,  
sum(damount) dsales , sum(camount) csales ,cu.symbol  
from vwcashsales cs, aaccountmaster am,  
ashops sh,adepartmentmaster ad,acurrencymaster cu  
where  
cs.transtype='PD CHEQUE' and  
cs.accountid = am.accountid and cs.companyid = am.companyid and cash=0 and  
sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
sh.shopid=cs.shopid and  
billdate=@dttransdate and cs.shopid =@intshopid  
group by cs.companyid ,cs.shopid, billdate, accountdesc ,cu.symbol  
--RefNo-1 ends  
union all  
select drcompanyid, drshopid, customername, drchequeno refereneceno, drdate, drAmount amount,  
drAmount * drdepexrate damount, drAmount * drexchangerate  camount,  
5 as type, 'Receipts Details' Trans, drAmount as mode, drAmount*drdepexrate as dmode,  
drAmount * drexchangerate as cmode, 0.0 sales, 0.0 dsales, 0.0 csales,cu.symbol  
from losDummyReceiptHeader rh, acustomermaster cm,  
ashops sh,adepartmentmaster ad,acurrencymaster cu  
where drcancelled=0 and rh.drcustomerid=cm.customerid and rh.drcompanyid=cm.companyid and  
sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
sh.shopid=drShopid and  
drdate=@dttransdate  and drshopid =@intshopid  
UNION ALL  
SELECT hprhCompanyID,hprhShopid,c.hpCustName,hprhchequeNo refereneceno,hprhREceiptDate,hprhReceiptAmount amount,  
hprhReceiptAmount * 1 damount,hprhReceiptAmount * 1 camount,  
6 as type,'HP Receipt' Trans,hprhReceiptAmount AS mode,hprhReceiptAmount * 1 AS dmode,  
hprhReceiptAmount * 1 cmode,0.0 sales,0.0 dsales,0.0 csales,cu.symbol  
FROM loshpReceiptHeader rh,loshpCustomerDetails c,  
ashops sh,adepartmentmaster ad,acurrencymaster cu  
WHERE hprhCancel=0 AND rh.hprhCustomerid=c.hpCustID AND rh.hprhCompanyid=c.hpCompanyID AND  
sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
hprhShopid=sh.Shopid AND  
hprhReceiptDate=@dttransdate AND hprhShopid=@intshopid  
union all  
--added to show  the labels after the groups  
select s.companyid, s.shopid, '' accountdesc, '', billdate, 0.0 amount, 0.0 damount, 0.0 camount,  
7 as type, 'Collection' as trans, 0.0 amount, 0.0 damount, 0.0 camount, 0.0 sales, 0.0 sales,  
0.0 sales,cu.symbol  
from ashops s, vwcashsales  c ,adepartmentmaster ad,acurrencymaster cu  
where s.shopid=c.shopid and s.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
billdate=@dttransdate  and s.shopid =@intshopid  
group by s.companyid,s.shopid,billdate,cu.symbol  
union all  
select phcompanyid, phshopid, phRemarks, phpaymentno referenceno, phPaymentDate, phAmount,  
phAmount* phdepexrate, phAmount * phexchangerate,  
8 as type, 'Payment Details' Trans, -phAmount as mode, -phAmount*phdepexrate as dmode,  
-phAmount* phexchangerate as cmode, 0.0 sales, 0.0 dsales, 0.0 csales,cu.symbol  
from  
LOsPaymentVoucherHeader ph ,ashops sh,adepartmentmaster ad,acurrencymaster cu  
where phcancelled=0 and sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
sh.shopid=phShopid and  
phpaymentdate=@dttransdate  and phshopid =@intshopid  
union all  
--added to show  the labels after the groups  
select s.companyid, s.shopid, '' accountdesc, '', billdate, 0.0 amount, 0.0 damount, 0.0 camount,  
9 as type, 'Amount After Payments' as trans, 0.0 amount, 0.0 damount, 0.0 camount, 0.0 sales,  
0.0 dsales, 0.0 csales,cu.symbol  
from  
ashops s, vwcashsales  c,adepartmentmaster ad,acurrencymaster cu  
where  
s.shopid=c.shopid and  
s.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
billdate=@dttransdate  and s.shopid =@intshopid  
group by s.companyid,s.shopid,billdate,cu.symbol  
union all  
select lphcompanyid,lphshopid,VendorName,lphBillNo reference,lphBillDate, lphBillAmount,  
lphBillAmount *lphdepexrate, lphBillAmount*lphexchangerate, 10 as type,'Local Purchases' as Trans,  
-lphbillamount as mode, -lphbillamount*lphdepexrate as dmode,  
-lphbillamount*lphexchangerate as cmode, 0.0 sales, 0.0 dsales , 0.0 csales ,cu.symbol from  
loslocalpurchaseheader lh,avendormaster v,  
ashops sh,adepartmentmaster ad,acurrencymaster cu  
where  
sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
sh.shopid=lphShopid and  
lphbilldate=@dttransdate and lphshopid=@intshopid  
and lphCashPurchase=1 and lh.lphvendorid=v.vendorid and lphCancelled=0  
union all  
--added to show  the labels after the groups  
select s.companyid, s.shopid, '' accountdesc, '', billdate, 0.0 amount, 0.0 damount, 0.0 camount,  
11 as type, 'Net COLLECTION' as trans, 0.0 amount, 0.0 damount, 0.0 camount, 0.0 sales,  
0.0 dsales , 0.0 csales,cu.symbol  
from ashops s, vwcashsales  c ,adepartmentmaster ad,acurrencymaster cu  
where  
s.shopid=c.shopid and s.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
billdate=@dttransdate  and s.shopid =@intshopid  
group by s.companyid,s.shopid,billdate,cu.symbol  
union all  
---RefNo-2   --commented  
--select ihcompanyid, ihshopid, customername, ihinvoiceno reference, ihinvoicedate, Amount,  
--dAmount, cAmount, 12 as type , 'Service Invoices' As Trans, Amount as mode, dAmount as dmode,  
--cAmount as cmode, Amount sales, dAmount dsales, cAmount csales,cu.symbol  
--from vwServiceInvoice, acustomermaster ,  
--ashops sh,adepartmentmaster ad,acurrencymaster cu  
--where ihcashinvoice=0 and ihcustomerid=customerid and  
--sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
--sh.shopid=ihShopid and  
--ihinvoicedate=@dttransdate and ihshopid =@intshopid  
-- Union All  
select ihcompanyid, ihshopid, customername, ihinvoiceno reference, ihinvoicedate, Amount,  
dAmount, cAmount, 13 as type , 'Credit Sales' As Trans, Amount as mode, dAmount as dmode,  
cAmount as cmode, Amount sales, dAmount dsales, cAmount csales,cu.symbol  
from vwcreditsales, acustomermaster ,  
ashops sh,adepartmentmaster ad,acurrencymaster cu  
where ihcashinvoice=0 and ihcustomerid=customerid and  
sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
sh.shopid=ihShopid and  
ihinvoicedate=@dttransdate and ihshopid =@intshopid  
and Amount>0 -- RefNo-1 added  
--UNION ALL  
--select hpqhCompanyID, hpqhShopID, c.hpCustName, hpqhQuotationNo reference, hpqhQuotationDate, hpqhInstPrice,  
--hpqhInstPrice, hpqhInstPrice, 13 as type , 'HP Invoice' As Trans, hpqhInstPrice as mode, hpqhInstPrice as dmode,  
--hpqhInstPrice as cmode, hpqhInstPrice sales, hpqhInstPrice dsales, hpqhInstPrice csales,cu.symbol  
--from loshpInvoiceHeader, loshpCustomerdetails c ,  
--ashops sh,adepartmentmaster ad,acurrencymaster cu  
--where hpqhCancel=0 AND hpqhtype='I' and hpqhCustomerID=hpCustID and  
--sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
--sh.shopid=hpqhShopID and  
--hpqhQuotationDate=@dttransdate and hpqhShopID =@intshopid  
union all  
--RefNo-3  
select lh.GrnCompanyID,lh.grnhShopid,CustomerName,lh.GrnhGoodsreturnnoteNO reference,  
lh.GrnhGoodsreturnnoteDate, -vw.goodsreturnamt amount, -vw.goodsreturnamt* grnhdepexrate damount,  
- vw.goodsreturnamt*grnhexchangerate camount,15 as type, 'Goods Return' as Trans,  
-- RefNo-1 start  
--0.0 as mode,0.0 as dmode, 0.0 as cmode,  
-vw.goodsreturnamt  as mode, -vw.goodsreturnamt* grnhdepexrate as dmode,  
-vw.goodsreturnamt*grnhexchangerate as cmode,  
-- RefNo-1 end  
0.0 as sales, 0.0 as dsales, 0.0 as csales ,cu.symbol  
from  
losgoodsreturnnoteheader lh,vwgoodsreturnamount vw,acustomermaster ac,  
ashops sh,adepartmentmaster ad,acurrencymaster cu  
where vw.GrnhGoodsreturnnoteID=lh.GrnhGoodsreturnnoteID and vw.grnhshopid=lh.grnhShopid  
and lh.GrnhCancel=0 and  
sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and sh.shopid=lh.grnhShopid and  
lh.GrnhGoodsreturnnoteDate=@dttransdate and lh.grnhShopid=@intshopid  
and ac.CustomerID=lh.GrnhCustomerID  
union all  
select s.companyid, s.shopid, '' accountdesc, '', billdate, 0.0 amount, 0.0 damount, 0.0 camount,  
16 as type, 'Total Sales' as trans, 0.0 amount, 0.0 damount, 0.0 camount, 0.0 sales, 0.0 dsales,  
0.0 csales ,cu.symbol  
from ashops s, vwcashsales  c,adepartmentmaster ad,acurrencymaster cu  
where  
s.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
s.shopid=c.shopid and  
billdate=@dttransdate  and s.shopid =@intshopid  
group by s.companyid,s.shopid,billdate ,cu.symbol  
UNION ALL  
---RefNo-2---------------  
select cs.companyid , cs.shopid, convert(varchar(10),TaxPercentage) + '% GST' as Description, '' as reference, billdate,  
sum(TaxAmount) amount, sum(DTaxAmount) damount, sum(CTaxAmount) camount, 17 as type, 'Collected Sales Tax Splitup' as trans,  
sum(TaxAmount) as mode, sum(DTaxAmount) as dmode, sum(CTaxAmount) as cmode,  
0.0 sales,0.0 dsales,0.0 csales, '' as symbol --,cu.symbol  
---------kept symbol as blank.becuase there can be cash/credit.so cannot link to accountmastre--------------  
from vwCollectedSalesTax cs  
--,aaccountmaster am,ashops sh,adepartmentmaster ad,acurrencymaster cu  
where --cs.accountid = am.accountid and cs.companyid = am.companyid and  
--sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and sh.shopid=cs.shopid and  
TaxPercentage<>0 and  
billdate=@dttransdate and cs.shopid =@intshopid  
group by cs.companyid ,cs.shopid, billdate,TaxPercentage  
--,accountdesc  
UNION ALL  
select cs.companyid , cs.shopid, convert(varchar(10),TaxPercentage) + '% GST' as Description, '' as reference, billdate,  
sum(TaxAmount) amount, sum(DTaxAmount) damount, sum(CTaxAmount) camount, 18 as type, 'Refunded Sales Tax Splitup' as trans,  
sum(-TaxAmount) as mode, sum(-DTaxAmount) as dmode, sum(-CTaxAmount) as cmode,  
0.0 sales,0.0 dsales,0.0 csales, '' as symbol --,cu.symbol  
---------kept symbol as blank.becuase there can be cash/credit.so cannot link to accountmastre--------------  
from vwRefundedSalesTax cs  
--, aaccountmaster am,ashops sh,adepartmentmaster ad,acurrencymaster cu  
where  
--cs.accountid = am.accountid and cs.companyid = am.companyid and  
--sh.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
--sh.shopid=cs.shopid and  
TaxPercentage<>0 and  
billdate=@dttransdate and cs.shopid =@intshopid  
group by cs.companyid ,cs.shopid, billdate,TaxPercentage  
--accountdesc ,cu.symbol,  
UNION ALL  
select s.companyid, s.shopid, '' accountdesc, '', billdate, 0.0 amount, 0.0 damount, 0.0 camount,  
19 as type, 'Total tax' as trans, 0.0 amount, 0.0 damount, 0.0 camount, 0.0 sales, 0.0 dsales,  
0.0 csales ,cu.symbol  
from ashops s, vwcashsales  c,adepartmentmaster ad,acurrencymaster cu  
where  
s.departmentid=ad.departmentid and cu.currencyid=ad.depcurrencyid and  
s.shopid=c.shopid and  
billdate=@dttransdate  and s.shopid =@intshopid  
group by s.companyid,s.shopid,billdate ,cu.symbol  
UNION ALL  
---RefNo-2---------------  
select 0, 0, '' , '', null, 0.0 amount, 0.0 damount, 0.0 camount,  
'' as type, '' as trans, 0.0 amount, 0.0 damount, 0.0 camount, 0.0 sales, 0.0 dsales ,  
0.0 csales ,''


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
  
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:wathania update
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE adminv2
GO
IF EXISTS( SELECT * FROM SYSOBJECTS WHERE XTYPE='P' 
AND NAME='spGetPurchaseRequestStatus')
BEGIN
	DROP PROCEDURE spGetPurchaseRequestStatus
END
GO 
/*  
CREATED BY : SHINE DAS  
CREATED ON : 07.09.2012  
COMMENT    : CREATED TO TRACE THE CURRENT STATUS OF SELECTED PURCHASE REQUESTS.    
-----------------------------
Ref : 01
ALTERED BY : SHINE DAS
ON		   : 18.09.2012
COMMENTED  : PR is not listing in report after approved by all (before generating PQ)
---------------------	
EXEC spGetPurchaseRequestStatus 60,1    
-
    
*/    
    
    
   
CREATE PROC spGetPurchaseRequestStatus ( @SpID AS INT, @DEPTID AS INT =0 )    
AS    
BEGIN --MAIN    
 DECLARE @PRID AS INT    
 DECLARE @POID AS INT    
 DECLARE @ApprovalEnabled AS INT    
 DECLARE @PRConfirmed AS BIT    
 DECLARE @PPOConfirmed AS BIT    
 DECLARE @POvConfirmed AS BIT    
     
 DECLARE @PONO AS VARCHAR(50)    
 DECLARE @PODate AS DATETIME    
 DECLARE @PRAmount AS NUMERIC (18,9)    
 DECLARE @LevelID AS INT    
 DECLARE @LevelName AS  VARCHAR(50)    
 DECLARE @ApprovalFrom AS  VARCHAR(200)    
 DECLARE @PQID AS INT    
 DECLARE @PQNO AS VARCHAR(50)    
 DECLARE @PQDate AS DATETIME    
 DECLARE @PQAmount AS NUMERIC (18,9)    
 DECLARE @CurrentSpID AS INT    
     
     
 set @PQID=0    
 set @PQNO=''    
 set @PQDate=''    
 set @PQAmount=0    
 DECLARE @PPOID AS INT    
 DECLARE @PPOCount AS INT    
 DECLARE @PPONO AS VARCHAR(50)    
 DECLARE @PPODate AS DATETIME    
 DECLARE @PPOAmount AS NUMERIC (18,9)    
 set @PPODate=''    
 set @PQID=0    
 set @PPOCount=0    
 set @PPONO=''    
 SET @PPOAmount=0    
 ---POvID--means purchase order verification    
 DECLARE @POvID AS INT    
 DECLARE @POvCount AS INT    
 DECLARE @POvNO AS VARCHAR(50)    
 DECLARE @POvDate AS DATETIME    
 DECLARE @POvAmount AS NUMERIC (18,9)    
 DECLARE @POvOnHold AS BIT    
 DECLARE @POvApproved AS BIT    
  set @POvDate=''    
 set @POvID=0    
 set @POvCount=0    
 set @POvNO=''    
 SET @POvAmount=0    
 SET @POvOnHold=0    
 SET @POvApproved=0    
 set @POID=0    
     
 DECLARE @PRuserID AS INT    
 DECLARE @PRUserName AS VARCHAR(100)    
 DECLARE @CreatedByID AS INT    
 DECLARE @CreatedByName AS VARCHAR(100)     
 DECLARE @DeptName AS VARCHAR(100)    
   
 SET @PRUserName=''    
 SET @DeptName=''  
     
 CREATE TABLE #tempStatus     
 (PRID INT,     
 PRNO varchar(50) NULL,    
  OrderID INT,     
  TID int NULL,     
  TType varchar (5),    
  TNo varchar(50) NULL,    
  TDate datetime NULL,    
  TAmount NUMERIC (18,9),    
  TRemarks Varchar(200),    
  PRCreatedBy Varchar(200) NULL,    
  CreatedBy Varchar(200) NULL,  
  DeptName Varchar(200) NULL)      
      
      
  --@POID,@CurrentSpID    
    
  IF @DEPTID<>0  
  BEGIN  
    
 SELECT @DeptName=departmentname from aDepartmentMaster where DepartmentID = @DEPTID  
   
  DECLARE PRCursor CURSOR FOR        
  SELECT PRID FROM tmpSELECTEDPR WHERE spid= @SpID    
    
  OPEN PRCursor     
  FETCH NEXT FROM PRCursor INTO @POID    
    
  WHILE @@FETCH_STATUS = 0     
  BEGIN     
   
  SELECT @ApprovalEnabled=NeedApproval FROm aPackagesettings    
     
  IF @ApprovalEnabled=1 and (select count(interfaceid) from aapprovaltransactions where interfaceid=2000)>0    
   BEGIN    
    SET @PRID=@POID    
      SELECT @PONO=pohpono,@PODate=pohPodate, @PRConfirmed=pohapproved, @PRAmount=pohValue, @PRuserID=pohuserID      
      FROM lopurchaseorderheader     
      where     
      pohpoID=@POID and pohDepartmentid=@DEPTID and pohtype='R'    
       
      SELECT @PRUserName=username from ausers where userid= @PRuserID    
        
    IF @PRConfirmed<>1 ----L1    
     BEGIN    
       SET @ApprovalFrom='Purchase Request not confirmed. And awating approval from'    
        DECLARE Levelcursor CURSOR FOR      
          select  a.levelid,a.levelname from aapprovallevelmaster a inner join     
          aapprovallevellimits b on a.levelid=b.levelid and a.InterfaceID=b.interfaceid     
          and a.departmentid = b.departmentid inner join aapprovallimitmaster c on     
          c.limitid=b.limitid and c.InterfaceID=b.interfaceid     
          and c.departmentid = b.departmentid                
         where a.levelid not in (select approvalstatuslevel from aapprovalstatus    
         where interfaceid=2000 and departmentid=@DEPTID and transactionid=@POID) and     
         @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@DEPTID     
         and c.interfaceid=2000 group by a.levelid,a.levelname    
                   
        OPEN Levelcursor       
        FETCH NEXT FROM Levelcursor INTO @LevelID,@LevelName       
         
        WHILE @@FETCH_STATUS = 0       
        BEGIN       
                   
          SET @ApprovalFrom = @ApprovalFrom + ' ' + @LevelName + ','    
                     
        FETCH NEXT FROM Levelcursor INTO @LevelID,@LevelName      
        END       
         
        CLOSE Levelcursor       
        DEALLOCATE Levelcursor     
               
      SET @ApprovalFrom=SUBSTRING ( @ApprovalFrom , 1 , LEN(@ApprovalFrom)-1 )     
      INSERT INTO #tempStatus VALUES(@PRID,@PONO,1,@POID,'PR',@PONO,@PODate,@PRAmount,@ApprovalFrom,@PRUserName,@CreatedByName,@DeptName)   
      GOTO PRCONTINUE          
     END----L1    
   ---Ref : 01 Added below line
   INSERT INTO #tempStatus VALUES(@PRID,@PONO,1,@POID,'PR',@PONO,@PODate,@PRAmount,'Purchase Request Approved, and Confirmed by Authorities.',@PRUserName,@CreatedByName,@DeptName)          
     ----L2      
   SELECT @PQID=pohpoid,@PQNO=pohpono,@PQDate=pohPodate, @PQAmount=pohValue, @CreatedByID=pohuserID       
   FROM lopurchaseorderheader     
   WHERE pohtype='Q' and pohQuotationid=@POID and pohDepartmentid=@DEPTID and pohcancel=0    
       
   SELECT @CreatedByName=username from ausers where userid= @CreatedByID    
       
   IF @PQID>0     
	   BEGIN    
	   INSERT INTO #tempStatus VALUES(@PRID,@PONO,2,@PQID,'PQ',@PQNO,@PQDate,@PRAmount,'Purchase Quotation Generated',@PRUserName,@CreatedByName,@DeptName)     
	   END   
   
 
	  
	    
     ----L2    
        
   SELECT @PPOID=pohpoid, @PPONO=pohpono,@PPOConfirmed=pohVerified, @PPODate=pohPodate,     
   @PPOAmount=pohValue, @PPOCount=count(*), @CreatedByID=pohuserID  FROM     
   loprepurchaseorderheader WHERE pohquotationid=@PQID and pohdepartmentID= @DEPTID     
   and pohcancel=0 GROUP BY pohpoid,pohpono,pohPodate,pohVerified,pohValue,pohuserID     
       
   SELECT @CreatedByName=username from ausers where userid= @CreatedByID    
   ---l3    
   IF @PPOCount>0    
    BEGIN    
      
      IF @PPOConfirmed<>1    
			  BEGIN    
			   SET @ApprovalFrom=''    
			   SET @ApprovalFrom='Pre-Purchase Order not confirmed. And awating approval from'    
				  DECLARE Levelcursor CURSOR FOR      
				   select  a.levelid,a.levelname from aapprovallevelmaster a inner join     
				   aapprovallevellimits b on a.levelid=b.levelid and a.InterfaceID=b.interfaceid     
				   and a.departmentid = b.departmentid inner join aapprovallimitmaster c on     
				   c.limitid=b.limitid and c.InterfaceID=b.interfaceid     
				   and c.departmentid = b.departmentid                
				  where a.levelid not in (select approvalstatuslevel from aapprovalstatus    
				  where interfaceid=2514 and departmentid=@DEPTID and transactionid=@PPOID) and     
				  @PPOAmount between c.lowerlimit and c.upperlimit and a.departmentid =@DEPTID     
				  and c.interfaceid=2514 group by a.levelid,a.levelname    
		              
				 OPEN Levelcursor       
				 FETCH NEXT FROM Levelcursor INTO @LevelID,@LevelName       
		    
				 WHILE @@FETCH_STATUS = 0       
				 BEGIN       
		              
				   SET @ApprovalFrom = @ApprovalFrom + ' ' + @LevelName + ','    
		                
					FETCH NEXT FROM Levelcursor INTO @LevelID,@LevelName      
				 END       
		    
				 CLOSE Levelcursor       
				 DEALLOCATE Levelcursor     
		           
			   SET @ApprovalFrom=SUBSTRING ( @ApprovalFrom , 1 , LEN(@ApprovalFrom)-1 )     
			  INSERT INTO #tempStatus VALUES(@PRID,@PONO,4,@PPOID,'PPO',@PPONO,@PPODate,@PRAmount,@ApprovalFrom,@PRUserName,@CreatedByName,@DeptName)      
		          
			  END    
	ELSE-----Ref : 01 Added Else part
		BEGIN
			INSERT INTO #tempStatus VALUES(@PRID,@PONO,3,@PPOID,'PPO',@PPONO,@PPODate,@PRAmount,'Pre-Purchase Order Approved, and Confirmed by Authorities.',@PRUserName,@CreatedByName,@DeptName)    
		END
		 
    END    
    ----l3 close    
        
 --pohpoonhold=0,pohApproved = 1, pohVerified  = 1    
       
    SELECT @POvID=pohpoid, @POvNO=pohpono,@POvConfirmed=pohVerified, @POvDate=pohPodate,     
   @POvAmount=pohValue,@POvOnHold=pohpoonhold,@POvApproved=pohApproved, @POvCount=count(*), @CreatedByID=pohuserID FROM     
   lopurchaseorderheader WHERE pohprepurchaseid=@PPOID and pohdepartmentID= @DEPTID     
   and pohcancel=0 GROUP BY pohpoid,pohpono,pohPodate,pohVerified,pohValue,pohpoonhold,pohApproved,pohuserID    
       
   SELECT @CreatedByName=username from ausers where userid= @CreatedByID    
       
   If @POvCount>0     
    BEGIN    
     INSERT INTO #tempStatus VALUES(@PRID,@PONO,5,@POvID,'PO',@POvNO,@POvDate,@PRAmount,'Purchase Order Generated',@PRUserName,@CreatedByName,@DeptName)     
         
     IF @POvOnHold<>0 AND @POvApproved<>1 and @POvConfirmed<>1    
      BEGIN    
       SET @ApprovalFrom=''    
       SET @ApprovalFrom='Purchase Order not confirmed. And awating approval from'    
          DECLARE Levelcursor CURSOR FOR      
           select  a.levelid,a.levelname from aapprovallevelmaster a inner join     
           aapprovallevellimits b on a.levelid=b.levelid and a.InterfaceID=b.interfaceid     
           and a.departmentid = b.departmentid inner join aapprovallimitmaster c on     
           c.limitid=b.limitid and c.InterfaceID=b.interfaceid     
           and c.departmentid = b.departmentid                
          where a.levelid not in (select approvalstatuslevel from aapprovalstatus    
          where interfaceid=2001 and departmentid=@DEPTID and transactionid=@POvID) and     
          @POvAmount between c.lowerlimit and c.upperlimit and a.departmentid =@DEPTID     
          and c.interfaceid=2001 group by a.levelid,a.levelname    
              
         OPEN Levelcursor       
         FETCH NEXT FROM Levelcursor INTO @LevelID,@LevelName       
    
         WHILE @@FETCH_STATUS = 0       
         BEGIN       
              
           SET @ApprovalFrom = @ApprovalFrom + ' ' + @LevelName + ','    
                
            FETCH NEXT FROM Levelcursor INTO @LevelID,@LevelName      
         END       
    
         CLOSE Levelcursor       
         DEALLOCATE Levelcursor     
           
       SET @ApprovalFrom=SUBSTRING ( @ApprovalFrom , 1 , LEN(@ApprovalFrom)-1 )     
      INSERT INTO #tempStatus VALUES(@PRID,@PONO,6,@POvID,'PO',@POvNO,@POvDate,@PRAmount,@ApprovalFrom,@PRUserName,@CreatedByName,@DeptName)      
      END    
    END    
      
  /*    
EXEC spGetPurchaseRequestStatus 19,1    
loPrePurchaseOrderHeader set pohVerified=1    
    
*/    
  END      
      
 ELSE    
  BEGIN    
   SELECT @PONO=pohpono,@PODate=pohPodate, @PRConfirmed=pohapproved FROM lopurchaseorderheader     
   where     
   pohpoID=@POID and pohDepartmentid=@DEPTID    
    IF @PRConfirmed<>1         
     BEGIN    
      INSERT INTO #tempStatus VALUES(@PRID,@PONO,2,@POID,'PR',@PONO,@PODate,@PRAmount,'Purchase Request Not Confirmed',@PRUserName,@CreatedByName,@DeptName)    
           
     END    
  END    
      
    PRCONTINUE:  
      FETCH NEXT FROM PRCursor INTO  @POID     
     END     
     CLOSE PRCursor     
     DEALLOCATE PRCursor     
END  
  
  
ELSE  ----COMPANYWISE  
  
  
BEGIN  
   
   
   DECLARE PRCursor CURSOR FOR        
  SELECT PRID FROM tmpSELECTEDPR WHERE spid= @SpID    
    
  OPEN PRCursor     
  FETCH NEXT FROM PRCursor INTO @POID    
    
  WHILE @@FETCH_STATUS = 0     
  BEGIN     
   
  SELECT @ApprovalEnabled=NeedApproval FROm aPackagesettings    
     
  IF @ApprovalEnabled=1 and (select count(interfaceid) from aapprovaltransactions where interfaceid=2000)>0    
   BEGIN    
    SET @PRID=@POID    
      SELECT @PONO=pohpono,@PODate=pohPodate, @PRConfirmed=pohapproved, @PRAmount=pohValue, @PRuserID=pohuserID, @DEPTID=pohDepartmentid    
      FROM lopurchaseorderheader     
      where     
      pohpoID=@POID  and pohtype='R'    
        
       SELECT @DeptName=departmentname from aDepartmentMaster where DepartmentID = @DEPTID  
       
      SELECT @PRUserName=username from ausers where userid= @PRuserID    
        
    IF @PRConfirmed<>1 ----L1    
     BEGIN    
       SET @ApprovalFrom='Purchase Request not confirmed. And awating approval from'    
        DECLARE Levelcursor CURSOR FOR      
          select  a.levelid,a.levelname from aapprovallevelmaster a inner join     
          aapprovallevellimits b on a.levelid=b.levelid and a.InterfaceID=b.interfaceid     
          and a.departmentid = b.departmentid inner join aapprovallimitmaster c on     
          c.limitid=b.limitid and c.InterfaceID=b.interfaceid     
          and c.departmentid = b.departmentid                
         where a.levelid not in (select approvalstatuslevel from aapprovalstatus    
         where interfaceid=2000 and departmentid=@DEPTID and transactionid=@POID) and     
         @PRAmount between c.lowerlimit and c.upperlimit and a.departmentid =@DEPTID     
         and c.interfaceid=2000 group by a.levelid,a.levelname    
                   
        OPEN Levelcursor       
        FETCH NEXT FROM Levelcursor INTO @LevelID,@LevelName       
         
        WHILE @@FETCH_STATUS = 0       
        BEGIN       
                   
          SET @ApprovalFrom = @ApprovalFrom + ' ' + @LevelName + ','    
                     
        FETCH NEXT FROM Levelcursor INTO @LevelID,@LevelName      
        END       
         
        CLOSE Levelcursor       
        DEALLOCATE Levelcursor     
               
      SET @ApprovalFrom=SUBSTRING ( @ApprovalFrom , 1 , LEN(@ApprovalFrom)-1 )     
      INSERT INTO #tempStatus VALUES(@PRID,@PONO,1,@POID,'PR',@PONO,@PODate,@PRAmount,@ApprovalFrom,@PRUserName,@CreatedByName,@DeptName)   
      GOTO PRCONTINUE2          
     END----L1    
         
     ----L2      
   SELECT @PQID=pohpoid,@PQNO=pohpono,@PQDate=pohPodate, @PQAmount=pohValue, @CreatedByID=pohuserID       
   FROM lopurchaseorderheader     
   WHERE pohtype='Q' and pohQuotationid=@POID and pohDepartmentid=@DEPTID and pohcancel=0    
       
   SELECT @CreatedByName=username from ausers where userid= @CreatedByID    
       
   IF @PQID>0     
   BEGIN    
   INSERT INTO #tempStatus VALUES(@PRID,@PONO,2,@PQID,'PQ',@PQNO,@PQDate,@PRAmount,'Purchase Quotation Generated',@PRUserName,@CreatedByName,@DeptName)     
   END    
     ----L2    
        
   SELECT @PPOID=pohpoid, @PPONO=pohpono,@PPOConfirmed=pohVerified, @PPODate=pohPodate,     
   @PPOAmount=pohValue, @PPOCount=count(*), @CreatedByID=pohuserID  FROM     
   loprepurchaseorderheader WHERE pohquotationid=@PQID and pohdepartmentID= @DEPTID     
   and pohcancel=0 GROUP BY pohpoid,pohpono,pohPodate,pohVerified,pohValue,pohuserID     
       
   SELECT @CreatedByName=username from ausers where userid= @CreatedByID    
   ---l3    
   IF @PPOCount>0    
    BEGIN    
     INSERT INTO #tempStatus VALUES(@PRID,@PONO,3,@PPOID,'PPO',@PPONO,@PPODate,@PRAmount,'Pre-Purchase Order Generated',@PRUserName,@CreatedByName,@DeptName)     
      IF @PPOConfirmed<>1    
      BEGIN    
       SET @ApprovalFrom=''    
       SET @ApprovalFrom='Pre-Purchase Order not confirmed. And awating approval from'    
          DECLARE Levelcursor CURSOR FOR      
           select  a.levelid,a.levelname from aapprovallevelmaster a inner join     
           aapprovallevellimits b on a.levelid=b.levelid and a.InterfaceID=b.interfaceid     
           and a.departmentid = b.departmentid inner join aapprovallimitmaster c on     
           c.limitid=b.limitid and c.InterfaceID=b.interfaceid     
           and c.departmentid = b.departmentid                
          where a.levelid not in (select approvalstatuslevel from aapprovalstatus    
          where interfaceid=2514 and departmentid=@DEPTID and transactionid=@PPOID) and     
          @PPOAmount between c.lowerlimit and c.upperlimit and a.departmentid =@DEPTID     
          and c.interfaceid=2514 group by a.levelid,a.levelname    
              
         OPEN Levelcursor       
         FETCH NEXT FROM Levelcursor INTO @LevelID,@LevelName       
    
         WHILE @@FETCH_STATUS = 0       
         BEGIN       
              
           SET @ApprovalFrom = @ApprovalFrom + ' ' + @LevelName + ','    
                
            FETCH NEXT FROM Levelcursor INTO @LevelID,@LevelName      
         END       
    
         CLOSE Levelcursor       
         DEALLOCATE Levelcursor     
           
       SET @ApprovalFrom=SUBSTRING ( @ApprovalFrom , 1 , LEN(@ApprovalFrom)-1 )     
      INSERT INTO #tempStatus VALUES(@PRID,@PONO,4,@PPOID,'PPO',@PPONO,@PPODate,@PRAmount,@ApprovalFrom,@PRUserName,@CreatedByName,@DeptName)      
          
      END    
    END    
    ----l3 close    
        
 --pohpoonhold=0,pohApproved = 1, pohVerified  = 1    
       
    SELECT @POvID=pohpoid, @POvNO=pohpono,@POvConfirmed=pohVerified, @POvDate=pohPodate,     
   @POvAmount=pohValue,@POvOnHold=pohpoonhold,@POvApproved=pohApproved, @POvCount=count(*), @CreatedByID=pohuserID FROM     
   lopurchaseorderheader WHERE pohprepurchaseid=@PPOID and pohdepartmentID= @DEPTID     
   and pohcancel=0 GROUP BY pohpoid,pohpono,pohPodate,pohVerified,pohValue,pohpoonhold,pohApproved,pohuserID    
       
   SELECT @CreatedByName=username from ausers where userid= @CreatedByID    
       
   If @POvCount>0     
    BEGIN    
     INSERT INTO #tempStatus VALUES(@PRID,@PONO,5,@POvID,'PO',@POvNO,@POvDate,@PRAmount,'Purchase Order Generated',@PRUserName,@CreatedByName,@DeptName)     
         
     IF @POvOnHold<>0 AND @POvApproved<>1 and @POvConfirmed<>1    
      BEGIN    
       SET @ApprovalFrom=''    
       SET @ApprovalFrom='Purchase Order not confirmed. And awating approval from'    
          DECLARE Levelcursor CURSOR FOR      
           select  a.levelid,a.levelname from aapprovallevelmaster a inner join     
           aapprovallevellimits b on a.levelid=b.levelid and a.InterfaceID=b.interfaceid     
           and a.departmentid = b.departmentid inner join aapprovallimitmaster c on     
           c.limitid=b.limitid and c.InterfaceID=b.interfaceid     
           and c.departmentid = b.departmentid                
          where a.levelid not in (select approvalstatuslevel from aapprovalstatus    
          where interfaceid=2001 and departmentid=@DEPTID and transactionid=@POvID) and     
          @POvAmount between c.lowerlimit and c.upperlimit and a.departmentid =@DEPTID     
          and c.interfaceid=2001 group by a.levelid,a.levelname    
              
         OPEN Levelcursor       
         FETCH NEXT FROM Levelcursor INTO @LevelID,@LevelName       
    
         WHILE @@FETCH_STATUS = 0       
         BEGIN       
              
           SET @ApprovalFrom = @ApprovalFrom + ' ' + @LevelName + ','    
                
            FETCH NEXT FROM Levelcursor INTO @LevelID,@LevelName      
         END       
    
         CLOSE Levelcursor       
         DEALLOCATE Levelcursor     
           
       SET @ApprovalFrom=SUBSTRING ( @ApprovalFrom , 1 , LEN(@ApprovalFrom)-1 )     
      INSERT INTO #tempStatus VALUES(@PRID,@PONO,6,@POvID,'PO',@POvNO,@POvDate,@PRAmount,@ApprovalFrom,@PRUserName,@CreatedByName,@DeptName)      
      END    
    END    
      
  /*    
EXEC spGetPurchaseRequestStatus 19,1    
loPrePurchaseOrderHeader set pohVerified=1    
    
*/    
  END      
      
 ELSE    
  BEGIN    
   SELECT @PONO=pohpono,@PODate=pohPodate, @PRConfirmed=pohapproved FROM lopurchaseorderheader     
   where     
   pohpoID=@POID and pohDepartmentid=@DEPTID    
    IF @PRConfirmed<>1         
     BEGIN    
      INSERT INTO #tempStatus VALUES(@PRID,@PONO,2,@POID,'PR',@PONO,@PODate,@PRAmount,'Purchase Request Not Confirmed',@PRUserName,@CreatedByName,@DeptName)    
           
     END    
  END    
      
    PRCONTINUE2:  
      FETCH NEXT FROM PRCursor INTO  @POID     
     END     
     CLOSE PRCursor     
     DEALLOCATE PRCursor   
       
       
END   
         
  SELECT * FROM #tempStatus ORDER BY ORDERID    
 DROP TABLE #tempStatus      
END ---END MAIN

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Wings requirement(Task-8)
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
GO
USE adminv2
GO
IF EXISTS( SELECT * FROM SYSOBJECTS WHERE XTYPE='P' 
AND NAME='spInsertFlights')
BEGIN
	DROP PROCEDURE spInsertFlights
END
GO 
  
-----------------------------------------------------------------------  
--Created on  : 08/Oct/2010  
--Created by : Praveen S  
--Comments : For Inserting the Details In Flights  
------------------------------------------------------------------------ 
--Ref.No:1 
--Modified on  : 19/09/2012  
--Modified by  : AADYAKUMAR.D.V 
--Comments     : Added new fields 
------------------------------------------------------------------------ 
create PROCEDURE [dbo].[spInsertFlights]  
@flghtopcompanyid INT,  
@flghtid INT,  
@flghtopid INT,  
@flghtno VARCHAR(50),  
@flghtdepday INT,  
@flghtdeptime DATETIME,  
@flghtremarks VARCHAR(250),  
@flghtactive BIT,
--Ref.No:1---start-- 
@AirlinesName varchar(200) ,
@TypeofCatering int ,
@ExpectedNumberOfPassangers int, 
@DelayDuration numeric(18,2),
@userid int
--Ref.No:1---end--   
AS BEGIN  
  SET NOCOUNT ON  
  INSERT INTO Flights(companyid,FlightID,FlightOpid,FlightNo,FlightDepDay,FlightDepTime,Remarks,Active,
  --Ref.No:1---start--
  AirlinesName,TypeofCatering,ExpectedNumberOfPassangers,DelayDuration,userid )  
  --Ref.No:1---end--
  VALUES  
  (@flghtopcompanyid,@flghtid,@flghtopid,@flghtno,@flghtdepday,@flghtdeptime,@flghtremarks,@flghtactive,
  --Ref.No:1---start--
  @AirlinesName,@TypeofCatering,@ExpectedNumberOfPassangers,@DelayDuration,@userid )    
  --Ref.No:1---end--
  SET NOCOUNT OFF  
END


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Wings requirement(Task-8)
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------

GO
USE adminv2
GO
IF EXISTS( SELECT * FROM SYSOBJECTS WHERE XTYPE='P' 
AND NAME='spUpdateFlights')
BEGIN
	DROP PROCEDURE spUpdateFlights
END
GO 
  
------------------------------------------------------------------------  
--Created on  : 08/Oct/2010  
--Created by : Praveen S  
--Comments : For Updating the Details of Flights  
------------------------------------------------------------------------
--Ref.No:1 
--Modified on  : 19/09/2012  
--Modified by  : AADYAKUMAR.D.V 
--Comments     : Added new fields 
------------------------------------------------------------------------   
Create PROCEDURE [dbo].[spUpdateFlights]  
@flghtopcompanyid INT,  
@flghtid INT,  
@prevflghtopid INT,  
@flghtopid INT,  
@flghtno VARCHAR(50),  
@flghtdepday INT,  
@flghtdeptime DATETIME,  
@flghtremarks VARCHAR(250),  
@flghtactive BIT,
--Ref.No:1---start-- 
@AirlinesName varchar(200) ,
@TypeofCatering int ,
@ExpectedNumberOfPassangers int, 
@DelayDuration numeric(18,2),
@userid int
--Ref.No:1---end--  
AS BEGIN  
  SET NOCOUNT ON  
  UPDATE Flights  
  SET FlightNo = @flghtno,FlightDepDay = @flghtdepday,  
  FlightDepTime = @flghtdeptime,Remarks=@flghtremarks,Active=@flghtactive,  
  FlightOpid = @flghtopid,
  --Ref.No:1---start--
  AirlinesName=@AirlinesName,
  TypeofCatering=@TypeofCatering,
  ExpectedNumberOfPassangers=@ExpectedNumberOfPassangers,
  DelayDuration=@DelayDuration,
  userid=@userid
  --Ref.No:1---end--  
  WHERE FlightOpid = @prevflghtopid AND FlightID = @flghtid AND companyid = @flghtopcompanyid  
  SET NOCOUNT OFF  
END



GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:YMG-445556
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

USE [adminv2]
GO

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

--------------------------------------------------------------------------------                    
-- This stored procedure is going to be useed to generate Inventory Forecast report                    
-- This report model is given by Echocam                    
--------------------------------------------------------------------------------                    
-- Coded By: Regin T.                    
-- Coded On: 16-04-2009      
--Modified By : YOgesh Joe    
--Modified On :12-05-2009                  
--------------------------------------------------------------------------------                    
-- spInventoryForecast 10      -- 6 Months                     
-- spInventoryForecast 100, 1,'',''3,4,5,6,7,8','1,2,3,4,5,6,7,8,9' -- 100 Days                    
/*                    
User may select one of the below options                    
Parameter: Stock Out in                     
 Next 3 months (A)                    
 Next 6 months (A)                    
 Next 9 months (A)                    
 Next 12 months (A)                    
 No of Days (A)                    
*/   
--------------------------------------------------------------------------------                    
--RefNo-1
--Modified by : Bijesh.B
--Modified on : 19-09-2012
--Ticket id   : YMG-445556 (Fino)
--------------------------------------------------------------------------------                                  

create proc [dbo].[spInventoryForecast]                     
	@intDuration        as int,  -- the number of months/days. e.g. 3 if user selects Stock Out In 3 Months                    
	@bitDurationInDays  as int = 0, -- 1 if duration is in days, 0 if duration is in months                    
	@strDepartmentId as varchar(50),      
	@strCategoryId as varchar(50)      
as                    
begin  -- procedure begins                    
                    
	set nocount on                     
	declare @ItemId as nvarchar(2000),      
			@GodownId as nvarchar(2000),      
			@ShopId as nvarchar(2000),      
			@strSQL as nvarchar(2000)                    
	declare @dtPackageDate   as datetime                    
	declare @intNoOfSaleDays as int                      
	declare @intDays1 as int                      
	declare @intDays2 as int -- Stores the days inbetween the reporting date and the selected future date                    
	declare @intDays3 as int                      
	declare @Monthname1 as varchar(10),                
			@Monthname2 as varchar(10),                
			@Monthname3 as varchar(10),                
			@Monthname4 as varchar(10),                
			@Monthname5 as varchar(10),                
			@Monthname6 as varchar(10),                
			@Monthname7 as varchar(10),                
			@Monthname8 as varchar(10),                
			@Monthname9 as varchar(10),                
			@Monthname10 as varchar(10),                
			@Monthname11 as varchar(10),                
			@Monthname12 as varchar(10),                
			@BeforeSelected as varchar(25),              
			@Selected as varchar(25),              
			@AfterSelected as varchar(25),              
			@DayORMonth as varchar(10)              
              
	-- Below variables store the beginning day of the respective months                     
	declare                      
			@dtMonthCurrent as datetime,                    
			@dtMonthOne     as datetime,                    
			@dtMonthTwo     as datetime,                    
			@dtMonthThree   as datetime,                    
			@dtMonthFour    as datetime,                    
			@dtMonthFive    as datetime,                    
			@dtMonthSix     as datetime,                    
			@dtMonthSeven   as datetime,                    
			@dtMonthEight   as datetime,                    
			@dtMonthNine    as datetime,                    
			@dtMonthTen     as datetime,                    
			@dtMonthEleven  as datetime,                    
			@dtMonthTwelve  as datetime                    
                    
	create table #CurrentStock	(                    
									csItemID int,  -- Current Stock Item ID                    
									csStock  numeric(18,2)
								)-- Current Stock Stock                     
	create table #OrderedItems	(                    
									oiItemID     int,  -- Ordered Items Item ID                    
									oiOrderedQty numeric(18,2)
								)                      
	create table #AverageSale	(                    
									asItemID     int,                     
									asAvgSaleQty numeric(18,2)
								)
	create table #MonthSale1	(                   
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale2	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale3	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale4	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale5	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale6	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale7	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale8	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale9	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale10	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale11	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale12	(                    
									msItemID  int,               
									msSaleQty numeric(18,2)
								)
	select @dtPackageDate = PackageDate from aPackageSettings                    
                    
	-- I. Getting the total stock in all locations of the company  -- Starts        
	create table #ItemIdTable	(	ItemId int	)      
	create table #ShopIdTable	(	ShopId int	)      
	create table #GodownIdTable	(   GodownId int	)      
	create table #DepartmentIdTable	(	DepartmentID int	)      
	if @strCategoryId<>''      
		begin      
			set @strSQL=N'      
			insert into #ItemIdTable      
			select ItemId from aitem where ItemCategoryID in ('+ @strCategoryId +')'      
			exec sp_executesql @strSQL      
		end      
	else      
		begin      
			insert into #ItemIdTable select ItemId from aitem       
		end      
      
	if @strDepartmentId<>''       
		begin      
			set @strSQL=N'      
			insert into #ShopIdTable       
			select ShopID from ashops where DepartmentID in('+ @strDepartmentId +')'       
			exec sp_executesql @strSQL      
   
			set @strSQL=N'      
			insert into #GodownIdTable      
			select GodownID from aGodown where DepartmentID in('+ @strDepartmentId +')'             
			exec sp_executesql @strSQL      
       
			set @strSQL=N'      
			insert into #DepartmentIdTable      
			select DepartmentID from adepartmentmaster where DepartmentID in('+@strDepartmentId+')'      
			exec sp_executesql @strSQL      
		end      
	else      
		begin      
			insert into #ShopIdTable select ShopID from ashops      
			insert into #GodownIdTable select GodownID from aGodown      
			insert into #DepartmentIdTable select DepartmentID from adepartmentmaster      
		end      
    
	insert into #CurrentStock                    
		select ItemID, sum(stock) Stock                    
		from             
		(	-- All Shop Stocks           
			select s.itemid ItemID, s.shopid LocationID, sum(s.stock) as Stock                     
			from  vwInquiryShopStock s        
			where s.itemid in (select * from #ItemIdTable)      
				and  s.shopid in(select * from #ShopIdTable)                
			GROUP BY s.shopid, s.itemid                    
                    
			union all                    
                    
			-- All Godown Stocks                    
			select gsitemid ItemID, gsGodownid LocationID, sum(gsstock) as Stock                    
			from vwInquiryGodownStock g      
			where g.gsitemid in (select * from #ItemIdTable)      
				and  g.gsGodownid in(select * from #GodownIdTable)             
			GROUP BY gsitemid, gsgodownid                    
		)a 
		group by ItemID                    
                  
		-- I. Getting the total stock in all locations of the company  -- Ends                     
        -- II. Finding the Purchase Ordered Quantities  -- Starts                     
                    
	insert into #OrderedItems                    
		select              
			podItemID, sum(podQty*Quantity) OrderedItemQty                     
		from      
			loPurchaseOrderHeader                     
			left outer join loPurchaseOrderDetail on  pohPoid=podPoid      
			left outer join aItem i on i.ItemID = podItemID                     
			left outer join aPackingTypeCapacityDetail c                     
			on c.PackingTypeID = podPackingTypeID and c.UnitsID = i.UnitsID                    
		where	  
			podPOID in	(
							select pohPOID from loPurchaseOrderHeader                     
							where pohbillgenerated=0 and pohpoid<>0 and pohcompanyid=1                     
								and pohcancel=0 AND left(pohtype,1)='P' and pohpoonhold = 0
						)      
			and podItemID in (select * from #ItemIdTable)      
			and pohDepartmentid in (select * from #DepartmentIdTable)      
			group by podItemID      
	-- II. Finding the Purchase Ordered Quantities  -- Ends                    
	-- III. Calculating the sale in the last 12 months -- Starts --                    
	-- Beginning of the current month                    
	set @dtMonthCurrent = dateadd("m", 0, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
               
	-- Beginning of of 1st previous month                    
	set @dtMonthOne = dateadd("m", -1, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
                    
	-- Beginning of the 2nd previous month                    
	set @dtMonthTwo = dateadd("m", -2, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
                    
	-- Beginning of the 3rd previous month                    
	set @dtMonthThree = dateadd("m", -3, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 4th previous month                    
	set @dtMonthFour =  dateadd("m", -4, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 5th previous month                    
	set @dtMonthFive = dateadd("m", -5, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 6th previous month                    
	set @dtMonthSix = dateadd("m", -6, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
                    
	-- Beginning of the 7th previous month                    
	set @dtMonthSeven = dateadd("m", -7, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 8th previous month                    
	set @dtMonthEight = dateadd("m", -8, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))          
	                    
	-- Beginning of the 9th previous month                    
	set @dtMonthNine = dateadd("m", -9, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 10th previous month                    
	set @dtMonthTen = dateadd("m", -10, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 11th previous month                    
	set @dtMonthEleven = dateadd("m", -11, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 12th previous month                    
	set @dtMonthTwelve = dateadd("m", -12, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
                    
	-- Sale in the 1st previous month                    
	insert into #MonthSale1                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                 
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthOne and poshBilldate < @dtMonthCurrent       
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                 
		group by posdItemID                    
	-- Sale in the 2nd previous month                    
	insert into #MonthSale2                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthTwo and poshBilldate < @dtMonthOne       
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                 
			group by posdItemID                   
                    
	-- Sale in the 3rd previous month                    
	insert into #MonthSale3                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthThree and poshBilldate < @dtMonthTwo       
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                   
		group by posdItemID      
                   
	-- Sale in the 4th previous month                   
	insert into #MonthSale4                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthFour and poshBilldate < @dtMonthThree                    
		and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)       
		group by posdItemID   
	                 
	-- Sale in the 5th previous month                    
	insert into #MonthSale5                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthFive and poshBilldate < @dtMonthFour                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)       
		group by posdItemID      
                  
	-- Sale in the 6th previous month                    
	insert into #MonthSale6                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthSix and poshBilldate < @dtMonthFive                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)       
		group by posdItemID      
                               
	-- Sale in the 7th previous month                    
	insert into #MonthSale7             
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthSeven and poshBilldate < @dtMonthSix       
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                    
		group by posdItemID                    
                       
	-- Sale in the 8th previous month                    
	insert into #MonthSale8                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales  
		where                    
			poshBilldate >= @dtMonthEight and poshBilldate < @dtMonthSeven                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)         
		group by posdItemID                    
	-- Sale in the 9th previous month                    
	insert into #MonthSale9                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthNine and poshBilldate < @dtMonthEight                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)         
			group by posdItemID                   
	                    
	-- Sale in the 10th previous month                    
	insert into #MonthSale10                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthTen and poshBilldate < @dtMonthNine                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)        
		group by posdItemID                    
	                 
	-- Sale in the 11th previous month                    
	insert into #MonthSale11                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthEleven and poshBilldate < @dtMonthTen                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)      
		group by posdItemID 
			
	-- Sale in the 12th previous month                    
	insert into #MonthSale12                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale 
		from vwShopItemSales                
		where                    
			poshBilldate >= @dtMonthTwelve and poshBilldate < @dtMonthEleven                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)      
		group by posdItemID      
	                
	-- III. Calculating the sale in the last 12 months -- Ends --                    
    -- IV. Finding Average Sale -- Starts here --                    
	set @intNoOfSaleDays = datediff("d",@dtMonthTwelve,@dtMonthCurrent)                    
	--set @intNoOfSaleDays = datediff("d",convert(datetime,@strSaleStartDate),convert(datetime,@strSaleEndDate))                    
	insert into #AverageSale                    
		select                     
			posdItemID ItemID,                     
			case                     
				when @intNoOfSaleDays = 0 then 0                   
				else                      
					convert(numeric(18,2),sum(posdquantity)/@intNoOfSaleDays)                     
			end AvgSale                    
		from vwShopItemSales                     
		where                     
			poshBilldate >= @dtMonthTwelve and poshBilldate < @dtMonthCurrent       
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                   
		group by posdItemID      
		            
	-- IV. Finding Average Sale -- Ends here --                    
                    
	-- V. Counting the days inbetween the reporting date and the future date  -- Starts                    
	if @bitDurationInDays = 1 -- If duration is specified in days                    
		begin                    
			set @intDays1 = @intDuration - 90  -- before 3 months                    
			if @intDays1 < 0 set @intDays1 = 0                    
			set @intDays2 = @intDuration                    
			set @intDays3 = @intDuration + 90  -- after 3 months                    
		end                    
	else                      -- If duration is specified in months                    
		begin                    
			set @intDays1 = datediff("d", @dtPackageDate, dateadd("m", @intDuration-3, @dtPackageDate))                      
			if @intDays1 < 0 set @intDays1 = 0                    
			set @intDays2 = datediff("d", @dtPackageDate, dateadd("m", @intDuration, @dtPackageDate))                      
			set @intDays3 = datediff("d", @dtPackageDate, dateadd("m", @intDuration+3, @dtPackageDate))                      
		end                    
	-- V. Counting the days inbetween the reporting date and the future date  -- Ends                    
	--VI.Making Before,Next and After Periods---Starts--              
	/*
	select @DayOrMonth=case @bitDurationInDays when 1 then 'Days' when 0 then 'Months' end              
	select @Selected='Next'+space(1)+rtrim(ltrim(str(@intDuration)))+space(1)+rtrim(ltrim(@DayOrMonth))              
	if @DayOrMonth='Months'              
		begin              
			if (@intDuration-3) >0              
				begin              
					select @BeforeSelected='Next'+space(1)+ltrim(rtrim(str(@intDuration-3)))+space(1)+@DayOrMonth              
				end              
			else              
				begin              
					select @BeforeSelected='Next'+space(1)+'0'+space(1)+'Months'              
				end              
		end              
	else -- Days              
		begin              
			if (@intDuration-90) >0              
				begin              
					select @BeforeSelected='Next'+space(1)+ltrim(rtrim(str(@intDuration-90)))+space(1)+@DayOrMonth              
				end              
			else              
				begin              
					select @BeforeSelected='Next'+space(1)+'0'+space(1)+'Days'              
				end              
		end              
	if @DayOrMonth='Months'              
		begin              
			select @AfterSelected='Next'+space(1)+rtrim(ltrim(str(@intDuration+3)))+space(1)+rtrim(ltrim(@DayOrMonth))              
		end              
	else              
		begin              
			select @AfterSelected='Next'+space(1)+rtrim(ltrim(str(@intDuration+90)))+space(1)+rtrim(ltrim(@DayOrMonth))              
		end              
	*/
	/*
	select @DayOrMonth=case @bitDurationInDays when 1 then 'D' when 0 then 'M' end              
	select @Selected=rtrim(ltrim(str(@intDuration)))
	if @bitDurationInDays=0 -- Months                  
		begin              
			if (@intDuration-3) >0              
				begin              
					select @BeforeSelected=ltrim(rtrim(str(@intDuration-3)))
				end              
			else              
				begin              
					select @BeforeSelected='0'
				end              
		end              
	else -- Days              
		begin              
			if (@intDuration-90) >0              
				begin              
					select @BeforeSelected=ltrim(rtrim(str(@intDuration-90)))
				end              
			else              
				begin              
					select @BeforeSelected='0'
				end              
		end              
	if @bitDurationInDays=0 -- Months             
		begin              
			select @AfterSelected=rtrim(ltrim(str(@intDuration+3)))
		end           
	else              
		begin              
			select @AfterSelected=rtrim(ltrim(str(@intDuration+90)))
		end              
	*/
	--select @DayOrMonth=case @bitDurationInDays when 1 then 'D' when 0 then 'M' end              
	select @DayOrMonth=''
	select @Selected=convert(varchar,@intDuration)--+' '+@DayOrMonth              
	if @bitDurationInDays=0 -- Months             
		begin              
			if (@intDuration-3) >0              
				begin              
					select @BeforeSelected=convert(varchar,@intDuration-3)+' '+@DayOrMonth              
				end              
			else              
				begin              
					select @BeforeSelected='0 '+@DayOrMonth             
				end              
		end              
	else -- Days              
		begin              
			if (@intDuration-90) >0              
				begin              
					select @BeforeSelected=convert(varchar,@intDuration-90)+' '+@DayOrMonth              
				end              
			else              
				begin              
					select @BeforeSelected='0 '+@DayOrMonth              
				end              
		end              
	if @bitDurationInDays=0 -- Months            
		begin              
			select @AfterSelected=convert(varchar,@intDuration+3)+' '+@DayOrMonth              
		end              
	else              
		begin              
			select @AfterSelected=convert(varchar,@intDuration+90)+' '+@DayOrMonth              
		end              
	--VI.Making Before,Next and After Periods---Ends--                     
	-- VII. Giving output -- Starts --                    
                
	SELECT  
		@Monthname1=substring(upper(DATENAME(month, DATEADD(month, -1, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -1, PAckageDate)),3,2),            
		@Monthname2=substring(upper(DATENAME(month, DATEADD(month, -2, PAckageDate))),1,3) +'-'+  substring(DATENAME(year,DATEADD(month, -2, PAckageDate)),3,2),            
		@Monthname3=substring(upper(DATENAME(month, DATEADD(month, -3, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -3, PAckageDate)),3,2),            
		@Monthname4=substring(upper(DATENAME(month, DATEADD(month, -4, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -4, PAckageDate)),3,2),            
		@Monthname5=substring(upper(DATENAME(month, DATEADD(month, -5, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -5, PAckageDate)),3,2),            
		@Monthname6=substring(upper(DATENAME(month, DATEADD(month, -6, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -6, PAckageDate)),3,2),            
		@Monthname7=substring(upper(DATENAME(month, DATEADD(month, -7, PAckageDate))),1,3) +'-'+  substring(DATENAME(year,DATEADD(month, -7, PAckageDate)),3,2),            
		@Monthname8=substring(upper(DATENAME(month, DATEADD(month, -8, PAckageDate))),1,3) +'-'+  substring(DATENAME(year,DATEADD(month, -8, PAckageDate)),3,2),            
		@Monthname9=substring(upper(DATENAME(month, DATEADD(month, -9, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -9, PAckageDate)),3,2),            
		@Monthname10=substring(upper(DATENAME(month, DATEADD(month, -10, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -10, PAckageDate)),3,2),            
		@Monthname11=substring(upper(DATENAME(month, DATEADD(month, -11, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -11, PAckageDate)),3,2),            
		@Monthname12=substring(upper(DATENAME(month, DATEADD(month, -12, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -12, PAckageDate)),3,2)             
	From aPAckageSettings                
                   
	select                     
		ItemID, ItemCode, ItemDescription, isnull(csStock,0) CurrentStock, isnull(oiOrderedQty,0) OrderedQty,                     
		isnull(csStock,0)+isnull(oiOrderedQty,0) CurrStockAndOrdered,  -- CS+O                    
		isnull(asAvgSaleQty,0) AverageSale,             
		convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays1) BalanceBefore3Months,                     
		convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays2) SufficientBalance,                    
		convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays3) BalanceAfter3Months,                    
		isnull(m12.msSaleQty,0) Month12, -- Oldest months are listed first                    
		isnull(m11.msSaleQty,0) Month11,                    
		isnull(m10.msSaleQty,0) Month10,                    
		isnull(m9.msSaleQty,0) Month9,                    
		isnull(m8.msSaleQty,0) Month8,                    
		isnull(m7.msSaleQty,0) Month7,                    
		isnull(m6.msSaleQty,0) Month6,                    
		isnull(m5.msSaleQty,0) Month5,                    
		isnull(m4.msSaleQty,0) Month4,                    
		isnull(m3.msSaleQty,0) Month3,                    
		isnull(m2.msSaleQty,0) Month2,                    
		isnull(m1.msSaleQty,0) Month1,            
		@Monthname12 Monthname12,            
		@Monthname11 Monthname11,            
		@Monthname10 Monthname10,            
		@Monthname9 Monthname9,              
		@Monthname8 Monthname8,            
		@Monthname7 Monthname7,            
		@Monthname6 Monthname6,            
		@Monthname5 Monthname5,            
		@Monthname4 Monthname4,              
		@Monthname3 Monthname3,            
		@Monthname2 Monthname2,            
		@Monthname1 Monthname1,            
		@Selected Selected,            
		@BeforeSelected BeforeSelected,            
		@AfterSelected AfterSelected              
	/*                    
	,case                    
		when isnull(csStock,0)+isnull(oiOrderedQty,0) >= convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays2) then                    
		'Inventory OK' --If CS+O(Currennt Stock + Ordered Qty) is enough for given period                    
		when isnull(csStock,0)+isnull(oiOrderedQty,0) >= convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays1) then                    
		'Order Soon'  --If CS+O is not enough for the given period'                    
		else                    
		'Order Urgently' --If CS+O is not enough for even half of the given period                    
		end                    
	Suggestion                    
	*/                    
	from                     
		aItem left outer join #CurrentStock on ItemID = csItemID                    
		left outer join #OrderedItems on ItemID = oiItemID                    
		left outer join #AverageSale on ItemID = asItemID                    
		left outer join #MonthSale12 m12 on ItemID = m12.msItemID                    
		left outer join #MonthSale11 m11 on ItemID = m11.msItemID                    
		left outer join #MonthSale10 m10 on ItemID = m10.msItemID                    
		left outer join #MonthSale9 m9 on ItemID = m9.msItemID                    
		left outer join #MonthSale8 m8 on ItemID = m8.msItemID                    
		left outer join #MonthSale7 m7 on ItemID = m7.msItemID                    
		left outer join #MonthSale6 m6 on ItemID = m6.msItemID                    
		left outer join #MonthSale5 m5 on ItemID = m5.msItemID                    
		left outer join #MonthSale4 m4 on ItemID = m4.msItemID                    
		left outer join #MonthSale3 m3 on ItemID = m3.msItemID                    
		left outer join #MonthSale2 m2 on ItemID = m2.msItemID                    
		left outer join #MonthSale1 m1 on ItemID = m1.msItemID                    
	where                    

--RefNo-1 start commented and added
--		isnull(csStock,0)+isnull(oiOrderedQty,0) < isnull(asAvgSaleQty,0)*@intDays2 -- if CS+O is less than sufficient stock                    
		isnull(csStock,0)+isnull(oiOrderedQty,0) > isnull(asAvgSaleQty,0)*@intDays2 -- if CS+O is less than sufficient stock                    
--RefNo-1 ends
	-- VI. Giving output -- Ends --                    
                    
	drop table #CurrentStock                    
	drop table #OrderedItems                    
	drop table #AverageSale                    
	drop table #MonthSale1                    
	drop table #MonthSale2                    
	drop table #MonthSale3                    
	drop table #MonthSale4                    
	drop table #MonthSale5                    
	drop table #MonthSale6                    
	drop table #MonthSale7                    
	drop table #MonthSale8                    
	drop table #MonthSale9                    
	drop table #MonthSale10                    
	drop table #MonthSale11                    
	drop table #MonthSale12                    
	drop table #ItemIdTable    
	drop table #ShopIdTable    
	drop table #GodownIdTable    
	drop table #DepartmentIdTable                    
	set nocount off                    
                    
end -- procedure ends                    
                    
-----------------------------------------------------------------------------------------------------------------                    

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Missing update from Manu for solving invoice issue on 20.09.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO


USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spDebtorAgeSum]    Script Date: 09/20/2012 10:06:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDebtorAgeSum]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDebtorAgeSum]
GO

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spDebtorAgeSum]    Script Date: 09/20/2012 10:06:26 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- Procedure  
-- Modified by   : Kishore  
-- Modified on  : 10/06/2003  
-- Comments  : Added the Having condition in each select query  
--                        (on comparison with v2)  
-----------------------------------------------------------------------------  
-- Modified by   : venki, Hariharan R  
-- Modified on  : 11/09/2003 ....240903 (added debtoraccid ), 08/01/2004  
-- Comments  : given isnull --then 0 for settledamt field  
--                        (on comparison with v2)  
-- Modified by   : venkitesh  
-- Modified on  : 11/09/2003 ....240903 (added debtoraccid )  
-- Comments  : given vwSettlements as derived table filtering customerid, depid and invoicedate  
-- Modified by   : venkitesh  , Hariharan  
-- Modified on  : 29/06/2004, 08/12/2004  
-- Comments  : Corrected ageing and due period basis of todate  
--           : Corrected the company wise report fetching removing departmentid condition on settlements query  
-----------------------------------------------------------------------------  
-- RefNo-1  
-- Modified by : Regin  
-- Modified on : 16-06-2010  
-- Comments    : To speed up the execution.  
-- Old technique had below tow steps:  
--   1. Fetch ALL rows of vwInvoices and vwsettlements  
--      into #tempvwInvoices and #tempvwsettlements respectively.  
--      Since all rows are fetched, it took huge time to complete.  
--   2. Required rows were fetched from #tempvwInvoices  
--      and #tempvwsettlements applying condition.  
-- New technique eliminates the temporary tables and has one step:  
--   1. Required rows are fetched direcly from vwInvoices  
--      and vwsettlements applying condition.  
--      Since rows are fetched on condition, fetch completes quickly.  
-- Time taken to generate the outstanding invoices report for one customer  
-- in Simdi DB is...  
--   In old technique: 3 Minues  
--   In new technique: 20 Seconds  
-----------------------------------------------------------------------------  
--RefNo:01  
--Modified By : VinothMurugan V.  
--Modified On : 06/08/2010  
--Purpose     : Adding Currencyid  
--------------------------------------------------------------------------  
--Modified By : SHINE  
--Modified On : 28/07/2011  
--Purpose     : When added to VSS some unwaned comments came. So removed it  
--  spdebtoragesum '20010101','20100805','',0,0,0,'',''  
--RefNo:02  
--Modified By : Jyothish.SR.  
-- Modified On : 27/03/2012  
--Purpose     : select *  statement is avoid in vwsettlements and vwinvinvoices  
-----------------------------------------------------------------------------  
--RefNo:03  
--Modified By : MANU
--Modified On : 25/08/2012  
--Purpose     : Adding SalesPersonName to show in the Outstanding Invoice report 
--------------------------------------------------------------------------
--spdebtoragesum '20120101','20120809','',0,0,'',''
CREATE PROCEDURE [dbo].[spDebtorAgeSum] (  
	@dtstartdate varchar(11),@dtinvdate as varchar(11),@intcustid varchar(1000),@intdepartid int,
	@intageTodate int=0 ,@intShopID int=0,@strCatName as Varchar(30)='', 
	@strGroupName as Varchar(30)=''  
)  
as  
begin  
	declare @strquery as nvarchar(4000)  
	declare @SettleCustId as varchar(1500), @Invcustid as varchar(1500)  
	declare @strShop as nvarchar(4000)  
	declare  @strCatCond as Varchar(300)  
	declare @strGroupCond as Varchar(300)  
	SET @SettleCustId = ''  
	set @Invcustid = ''  
	set @strShop = ''  
	set @strCatCond=''  
	set @strGroupCond=''  
	Create table #tmpInvoices (
		CompanyID int,shopid int,DepartmentID int,InvoiceID int,customerid int,invoicedate datetime,  
		invoiceno varchar(50),Referenceno varchar (100),remarks varchar(1000),InvAmt numeric(18,2),  
		Due varchar(7),Type varchar(7),Debtortype varchar(50),updatetime datetime,  
		CustomerCategory varchar(100),duedate datetime ,depexrate numeric(18,2),InterFaceID int ,  
		SalesPersonID int,CustomerType char(1),DutyAmt numeric(18,2),CostPrice numeric(18,4),  
		CustGroupName varchar(100), TaxAmount numeric (18,2),age int  
	)  
	Create Table #tmpSettlements( 
		customerid int,ReceiptNo varchar(50),companyid int,invoiceid int,shopid int,settleddate datetime,  
		departmentid int,settledamt numeric(18,2),Type varchar(50)
	)  
	-- Commented (RefNo-1)  
	-- select * into #tempvwInvoices from vwInvoices  
	-- select * into #tempvwsettlements from vwsettlements  
	if @strCatName<>''  
		begin  
			set @strCatCond = ' CustomerCategory = ''' + @strCatName + ''' And '  
		end  
	if @strGroupName<>''  
		begin  
			set @strGroupCond = ' CustGroupName = ''' + @strGroupName + ''' And '  
		end  
	if @intShopID > 0  
		Begin  
			set @strShop=' And  #tmpInvoices.shopid = ' + cast(@intShopID As varchar)  
		end  
	if @intcustid<>''    --hari given to handle with out customerid also  
		Begin  
			set @SettleCustId = ' customerid in (' + @intcustid + ') and'  
			set @Invcustid = 'vwInvoices.customerid in (' + @intcustid + ') and'  
		End  
	-- if @dtstartdate =''  
	-- Begin  
	--    if @intdepartid >0  
	--    set @strquery ='insert #tmpInvoices  
	--     Select *,0 from #tempvwInvoices vwInvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
	--     ' invoicedate <=''' + @dtinvdate + '''' +  
	--     ' and departmentid = ' + cast(@intdepartid as varchar)  
	--    else  
	--     set @strquery ='insert #tmpInvoices  
	--     Select *,0 from #tempvwInvoices vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
	--     ' invoicedate <=''' + @dtinvdate + ''''  
	--    End  
	-- Else  
	-- Begin  
	--  if @intdepartid >0  
	--     set @strquery ='insert #tmpInvoices  
	--     Select *,0 from #tempvwInvoices vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
	--     ' invoicedate <=''' + @dtinvdate + '''' +  
	--     ' and departmentid = ' + cast(@intdepartid as varchar) +  
	--     ' and invoicedate >=''' + @dtstartdate + ''''  
	--  else  
	--   set @strquery ='insert #tmpInvoices  
	--   Select *,0 from #tempvwInvoices vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
	--      ' invoicedate <=''' + @dtinvdate + '' +  
	--   ''' and invoicedate >=''' + @dtstartdate + ''''  
	-- End  
	-- Instead of selecting from #tempvwInvoices,  
	-- required rows are fetched direcly from vwInvoices applying condition.  
	-- Thus increasing speed. Old code commented above. (RefNo-1)  
	if @dtstartdate =''  
		Begin  
			if @intdepartid >0  
				--RefNo:02  
				set @strquery ='insert #tmpInvoices  
					Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,
					Referenceno,remarks,InvAmt,Due,Type,Debtortype,updatetime,CustomerCategory,duedate,
					depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,CostPrice,CustGroupName,
					TaxAmount,0 from vwInvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
					' invoicedate <=''' + @dtinvdate + '''' +  
					' and departmentid = ' + cast(@intdepartid as varchar)  
			else  
				--   RefNo:02  
				set @strquery ='insert #tmpInvoices 
					Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,
					Referenceno,remarks,InvAmt,Due,Type,Debtortype,updatetime,CustomerCategory,duedate,
					depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,CostPrice,CustGroupName,
					TaxAmount ,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
					' invoicedate <=''' + @dtinvdate + ''''  
		End  
	Else  
		Begin  
			if @intdepartid >0  
				set @strquery ='insert #tmpInvoices  
					Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,
					Referenceno,remarks,InvAmt,Due,Type,Debtortype,updatetime,CustomerCategory,duedate,
					depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,CostPrice,CustGroupName,
					TaxAmount ,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
					' invoicedate <=''' + @dtinvdate + '''' + ' and departmentid = ' + 
					cast(@intdepartid as varchar) + ' and invoicedate >=''' + @dtstartdate + ''''  
			else  
				set @strquery ='insert #tmpInvoices  
					Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,
					Referenceno,remarks,InvAmt,Due,Type,Debtortype,updatetime,CustomerCategory,duedate,
					depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,CostPrice,CustGroupName,
					TaxAmount ,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
					' invoicedate <=''' + @dtinvdate + '' + ''' and invoicedate >=''' + @dtstartdate + ''''  
		End  
	exec sp_Executesql @strquery  
	--  if @dtstartdate =''  
	--  Begin  
	--  if @intdepartid >0  
	--   set @strquery  = ' insert #tmpSettlements Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +  
	--   ' departmentid = ' + cast(@intdepartid as varchar) +  
	--   ' and settleddate <=''' + @dtinvdate +  ''''  
	--  else  
	--   set @strquery  = 'insert #tmpSettlements  Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +  
	--      ' settleddate <=''' + @dtinvdate + ''''  
	--  
	--  End  
	--    Else  
	--    Begin  
	--  if @intdepartid >0  
	--   set @strquery  = ' insert #tmpSettlements Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +  
	--      ' departmentid = ' + cast(@intdepartid as varchar) +  
	--   ' and settleddate <=''' + @dtinvdate +  '' +  
	--   ''' and settleddate >=''' + @dtstartdate + ''''  
	--   else  
	--   set @strquery  = 'insert #tmpSettlements  Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +  
	--      ' settleddate <=''' + @dtinvdate + '' +  
	--   ''' and settleddate >=''' + @dtstartdate + ''''  
	--  
	--   End  
	-- Instead of selecting from #tempvwsettlements,  
	-- required rows are fetched direcly from vwsettlements applying condition.  
	-- Thus increasing speed. Old code commented above. (RefNo-1)  
	if @dtstartdate =''  
		Begin  
			if @intdepartid >0  
				--RefNo:02  
				set @strquery  = ' insert #tmpSettlements Select customerid,ReceiptNo,companyid,
					invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where 
					' + @SettleCustId +  ' departmentid = ' + cast(@intdepartid as varchar) +  
					' and settleddate <=''' + @dtinvdate +  ''''  
			else                             
				set @strquery  = 'insert #tmpSettlements  Select customerid,ReceiptNo,companyid,
					invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where ' 
					+ @SettleCustId + ' settleddate <=''' + @dtinvdate + ''''  
		End  
	Else  
		Begin  
			if @intdepartid >0  
				set @strquery  = ' insert #tmpSettlements Select customerid,ReceiptNo,companyid,
					invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where 
					' + @SettleCustId +  ' departmentid = ' + cast(@intdepartid as varchar) +  
					' and settleddate <=''' + @dtinvdate +  '' +  ''' and settleddate >=''' + 
					@dtstartdate + ''''  
			else  
				--   RefNo:02  
				set @strquery  = 'insert #tmpSettlements Select customerid,ReceiptNo,companyid,
					invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where 
					' + @SettleCustId + ' settleddate <=''' + @dtinvdate + '' +  
					''' and settleddate >=''' + @dtstartdate + ''''  
		End		
	exec sp_Executesql @strquery  
	-----RefNo:01  
	
	--<<RefNo:03 >> Comment the previous query and add new
	--<<Old Query>>
	--set @strquery = 'SELECT  max(invamt) invamt,isnull(sum(settledamt),0) settleamt,
	--	#tmpInvoices.invoiceid,#tmpInvoices.customerid,#tmpInvoices.shopid,#tmpInvoices.due,
	--	#tmpInvoices.invoicedate,#tmpInvoices.invoiceno,#tmpInvoices.type,remarks,customername,
	--	currencyname,symbol, #tmpInvoices.duedate,datediff(dd,#tmpInvoices.duedate, ''' + @dtinvdate + 
	--	''' ) overduedays, address1, address2, address3,#tmpInvoices.referenceno,debtoraccid,
	--	b.accountdesc, aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID FROM  
	--	#tmpInvoices #tmpInvoices LEFT OUTER JOIN #tmpSettlements vwsettlements ON 
	--	#tmpInvoices.customerid = vwsettlements.customerid AND  #tmpInvoices.CompanyID = 
	--	vwsettlements.companyid AND  #tmpInvoices.InvoiceID = vwsettlements.invoiceid AND  
	--	#tmpInvoices.type = vwsettlements.type AND  #tmpInvoices.shopid = vwsettlements.shopid  and  
	--	(vwsettlements.settleddate<=''' + @dtinvdate + ''' or vwsettlements.settleddate is null),  
	--	aCurrencyMaster,aCustomerMaster,aAccountMaster b WHERE #tmpInvoices.customerid = 
	--	aCustomerMaster.CustomerID AND  #tmpInvoices.CompanyID = aCustomerMaster.CompanyID and  
	--	aCustomerMaster.CurrencyID = aCurrencyMaster.CurrencyID AND aCustomerMaster.CompanyID = 
	--	aCurrencyMaster.CompanyID and  aCustomerMaster.debtorAccID = b.AccountID ' + @strShop  + '  
	--	and  #tmpInvoices.invoicedate<=''' + @dtinvdate + '''  group by #tmpInvoices.invoiceid,
	--	#tmpInvoices.departmentid,#tmpInvoices.customerid, #tmpInvoices.shopid,due ,invoicedate,  
	--	invoiceno,#tmpInvoices.type,remarks,customername,currencyname,symbol,#tmpInvoices.duedate,  
	--	address1, address2, address3, #tmpInvoices.referenceno,debtoraccid,b.AccountDesc ,
	--	aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID  
	--	having max(invamt) <> sum(isnull(settledamt,0))'  
	--<<Old Query>>
	--<<New Query>>
	set @strquery = 'SELECT  max(invamt) invamt,isnull(sum(settledamt),0) settleamt,
		#tmpInvoices.invoiceid,#tmpInvoices.customerid,#tmpInvoices.shopid,#tmpInvoices.due,
		#tmpInvoices.invoicedate,#tmpInvoices.invoiceno,#tmpInvoices.type,remarks,customername,
		currencyname,symbol, #tmpInvoices.duedate,datediff(dd,#tmpInvoices.duedate, ''' + @dtinvdate + 
		''' ) overduedays, address1, address2, address3,#tmpInvoices.referenceno,debtoraccid,
		b.accountdesc, aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID 
		,isnull(sp.Spername,'''')SalesPerson
		FROM  #tmpInvoices #tmpInvoices LEFT OUTER JOIN #tmpSettlements vwsettlements ON 
		#tmpInvoices.customerid = vwsettlements.customerid AND  #tmpInvoices.CompanyID = 
		vwsettlements.companyid AND  #tmpInvoices.InvoiceID = vwsettlements.invoiceid AND  
		#tmpInvoices.type = vwsettlements.type AND  #tmpInvoices.shopid = vwsettlements.shopid  and  
		(vwsettlements.settleddate<=''' + @dtinvdate + ''' or vwsettlements.settleddate is null)
		left outer join AsalesPersonmaster sp on sp.Sperid=isnull(#tmpInvoices.SalesPersonID,0),  
		aCurrencyMaster,aCustomerMaster,aAccountMaster b WHERE #tmpInvoices.customerid = 
		aCustomerMaster.CustomerID AND  #tmpInvoices.CompanyID = aCustomerMaster.CompanyID and  
		aCustomerMaster.CurrencyID = aCurrencyMaster.CurrencyID AND aCustomerMaster.CompanyID = 
		aCurrencyMaster.CompanyID and  aCustomerMaster.debtorAccID = b.AccountID ' + @strShop  + '  
		and  #tmpInvoices.invoicedate<=''' + @dtinvdate + '''  group by #tmpInvoices.invoiceid,
		#tmpInvoices.departmentid,#tmpInvoices.customerid, #tmpInvoices.shopid,due ,invoicedate,  
		invoiceno,#tmpInvoices.type,remarks,customername,currencyname,symbol,#tmpInvoices.duedate,  
		address1, address2, address3, #tmpInvoices.referenceno,debtoraccid,b.AccountDesc ,
		aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID  
		,sp.Spername
		having max(invamt) <> sum(isnull(settledamt,0))'  
	--<<New Query>>
	if @intageTodate=1  
		begin  
			update #tmpInvoices set age=datediff(day,invoicedate,CONVERT(DATETIME, @dtinvdate,102))  
			update #tmpInvoices set due =  case when (age  >=0 and age <= 30) then '0 - 30'  
				when (age  >=31 and age <= 60)  then '31 - 60'  
				when (age  >=61 and age <= 90) then '61 - 90'  
				when (age  >=91) then ' > 90' else '' end  
		end  
	exec sp_Executesql @strquery  
	--select * from #tempvwsettlements  
	-- Commented (RefNo-1)  
	-- drop table #tempvwInvoices  
	-- drop table #tempvwsettlements  
drop table #tmpInvoices  
drop table #tmpSettlements  
end
GO





GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Ticket/Task ID:Update Received from Aaadyakumar on 20.09.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

USE [adminv2]
GO

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


 
---Created By : Bijesh.B  
--Date       : 07/11/2011  
--Ref No.    : RefNo-1  
--Des : this is a copy of spUpdateCostingMethodPrice  
--      Since Sonee reported ODBC-Time Out error,  
--      to overcome this issue, instead of  taking stock from  
--  vwinquiryshopstock in this sp, we use vwinquiryshopstockSummary  
--      and used vwInquiryGodownStockSummary instead of vwInquiryGodownStock  
--modified by  : jyothish  
--modified Date : 01/02/2012  
--prevoius  stock and costprice insert to losCosAvlStock  
----------------------------------------------------------------
--modified by   : AADYAKUMAR  
--modified Date : 20/09/2012  
--modification  : numeric(18,2) is extended to numeric(18,8) to achieve maximum fraction
----------------------------------------------------------------
Create proc [dbo].[spUpdateCostingMethodPriceSummary] (@intItemID as int, @CostPrice as numeric(18,8),  
@intBillID as int, @numWAVGAmt as numeric(18,8)  output  
) as  
begin  
declare @IntCostingID as int  
declare @numTotal numeric(18,8)  
declare @numGdnQty numeric(18,8)  
declare @numShopQty numeric(18,8)  
declare @numTotalQty numeric(18,8)  
declare @numBillQty numeric(18,8)  
declare @numItemUP numeric(18,8)   -- from Item Master  
declare @numnoncosteditems as numeric(18,8)  
declare @numprocpendqtystock as numeric(18,8)  
declare @numothershipments as numeric(18,8),  
@numprevunreceivedqty as numeric(18,8),  
@numprevunconfirmedqty as numeric(18,8),  
@numnondespbillqty as numeric(18,8)  
set @numWAVGAmt = 0.00  
set @numTotal = 0.00  
set @numGdnQty = 0.00  
set @numShopQty = 0.00  
set @numBillQty = 0.00  
set @numItemUP = 0.00  
set @numprocpendqtystock = 0.0  
set @numothershipments =0.0  
set @numprevunreceivedqty = 0.0  
set @numprevunconfirmedqty = 0.0  
set @numnondespbillqty =0.0  
Select @numprocpendqtystock = isnull(sum(isnull(Transqty,0)),0) from vwquantityunprocessed  
where itemid = @intitemid  and type<>'Shipment Arrival' --type added to  
--avoid shipment arrivals which made restriction of despatch note generation  
--before costing.  
-- to get the bill qty from previous bills which are not yet despatched but costed  
Select @numnondespbillqty  = isnull(sum(isnull(pbdItemQuantity,0) * pk.quantity),0)  
from losppurchasebillheader, losppurchasebilldetail , aitem ai,  
aPackingTypeCapacityDetail pk where  pbhtobedespatched=1 and  
pbhcancelled=0 and pbhused= 1 and pbhdespatched = 0 and pbhbillid = pbdbillid and  
pbditemid=ai.itemid and ai.unitsid=pk.unitsid and pbdpackingtypeid=pk.packingtypeid  
and pbhbillid < @intBillID and pbditemid = @intItemID  
--to get the un confirmed stock in godowns from previous bills  
Select @numprevunconfirmedqty = isnull(sum(isnull(ad.adDespatchedQty,0) * pk.quantity),0)  
from ahqdespatchnotemain, ahqdespatchnoteheader , loiarrivalheader ah,  
loiarrivaldetail ad, aitem ai, aPackingTypeCapacityDetail pk where  
ah.ahcancelled=0 and ah.ahtransfinished= 0 and ah.aharrivalid=ad.adarrivalid and  
ah.ahlocalgodownid=ad.adgodownid and ad.aditemid=ai.itemid  
and ai.unitsid=pk.unitsid and ad.adpackingtypeid=pk.packingtypeid  
and dnmdespatchnoteid = dhdespatchnotemainid and dhdespatchnoteid  
=ahdespatchnoteid and dhgodownid = ahlocalgodownid and dnmbillid < @intBillID  
and aditemid = @intItemID  
Select @numprevunconfirmedqty  = @numprevunconfirmedqty  + ISNULL(sum(gadItemGoodQuantity),0)  
from ahqdespatchnotemain dnm,  ahqdespatchnoteheader dh, losGoodsArrivalToShopHeader ah,  
losGoodsArrivalToShopDetail ad where dh.dhcancelled=0 and dh.dhtransfinished = 1 and  
dh.dhdespatchnoteid = ah.gahhqdespatchid and dh.dhShopId = ah.gahShopId and  
gaharrivalid = ad.gadarrivalid and gahShopId = ad.gadShopId and ah.gahcancelled = 0 and  
gahtransfinished=0 and dnmdespatchnoteid = dhdespatchnotemainid and gaditemid = @intitemid  
and dnmbillid < @intbillid  
--Despatches not received in godowns from previous bills  
Select  @numprevunreceivedqty = isnull(sum(isnull(dd.ddQty,0) * pk.quantity),0) from  
ahqdespatchnotemain dnm,  ahqdespatchnoteheader dh, ahqdespatchnotedetails dd, aitem ai,  
aPackingTypeCapacityDetail pk where dh.dhcancelled=0 and dh.dhtransfinished= 1  
and dh.dhdespatchnoteid = dd.dddespatchnoteid and  
((dh.dhgodownid = dd.ddgodownid and dh.dhGodownId is not Null) or  
(dh.dhShopid = dd.ddShopId and dh.dhShopId is not Null)) and  
dd.dditemid = ai.itemid and dhselected =0 and  
ai.unitsid=pk.unitsid and dd.ddpackingtypeid=pk.packingtypeid and  
dnmdespatchnoteid = dhdespatchnotemainid and dnmbillid < @intBillID and dditemid = @intItemID  
--TO TAKE SHIPMENT QTY FROM OTHER SHIPMENTS and THE CURRENT SHIPMENT  
-- which have been updated to the stock (ARRIVAL TO GODOWN)  
Select @numothershipments = ISNULL(sum(isnull(ad.adReceivedQty,0) * isnull(pk.quantity,0)),0) from  
ahqdespatchnotemain dnm,  ahqdespatchnoteheader dh, loiarrivalheader ah, aitem ai,  
aPackingTypeCapacityDetail pk, Agodown gd, loiarrivaldetail ad where dh.dhcancelled=0 and  
dh.dhtransfinished= 1 and dh.dhdespatchnoteid = ah.ahdespatchnoteid and  
dh.dhgodownid = ah.ahlocalgodownid and aharrivalid = ad.adarrivalid and  
ahlocalgodownid = ad.adgodownid and ah.ahcancelled = 0 and aditemid = ai.itemid  
and ahtransfinished=1 and dhgodownid = gd.godownid and ai.unitsid=pk.unitsid and  
ad.adpackingtypeid=pk.packingtypeid and dnmdespatchnoteid = dhdespatchnotemainid  
and aditemid = @intitemid and dnmbillid >= @intbillid  
--TO TAKE SHIPMENT QTY FROM OTHER SHIPMENTS and THE CURRENT SHIPMENT  
-- which have been updated to the stock (ARRIVAL TO SHOP DIRECT)  
Select @numothershipments = @numothershipments + ISNULL(sum(gadItemGoodQuantityArrived),0)  
from ahqdespatchnotemain dnm,  ahqdespatchnoteheader dh, losGoodsArrivalToShopHeader ah,  
losGoodsArrivalToShopDetail ad where dh.dhcancelled=0 and dh.dhtransfinished= 1 and  
dh.dhdespatchnoteid = ah.gahhqdespatchid and dh.dhShopId = ah.gahShopId and  
gaharrivalid = ad.gadarrivalid and gahShopId = ad.gadShopId and ah.gahcancelled = 0 and  
gahtransfinished=1 and dnmdespatchnoteid = dhdespatchnotemainid and gaditemid = @intitemid  
and dnmbillid >= @intbillid  
Select @numItemUP = isnull(ItemRate,0) from aitem where itemid = @intItemID  
--RefNo-1 start commented and added  
--   Select @numGdnQty = isnull(sum(isnull(gsstock,0)),0) from vwinquirygodownstock where --  
--   gsitemid = @intItemID  
Select @numGdnQty = isnull(sum(isnull(gsstock,0)),0) from vwInquiryGodownStockSummary where  
gsitemid = @intItemID  
--Select @numShopQty = isnull(sum(isnull(stock,0)),0) from vwinquiryshopstock where  
--itemid = @intItemID  
Select @numShopQty = isnull(sum(isnull(stock,0)),0) from vwInquiryShopStockSummary where  
itemid = @intItemID  
--RefNo-1 ends  
Select @intcostingid = chCostingID from loacostingheader where chBillID = @intBillid  
and chCancelled=0  
Select @numBillQty = cdItemQuantity from loacostingdetail where cdcostingid = @intcostingid  
and cditemid = @intItemid  
set @numtotalqty = isnull(@numGdnQty,0) + isnull(@numShopQty,0)  +  
isnull(@numprocpendqtystock,0) +  isnull(@numprevunreceivedqty,0)  +  
isnull(@numprevunconfirmedqty,0) + isnull(@numnondespbillqty,0)  
- isnull(@numothershipments ,0)  
insert into losCosAvlStock (CompanyId,CostingID,ItemID,OldStock) values(1,@IntCostingID,@intItemID,@numtotalqty)  
if @numtotalqty < 0  
set @numtotalqty = 0  
set @numTotal = (@numBillQty * @costPrice) + (isnull(@numtotalqty,0) * isnull(@numItemUP,0))  
set @numWAVGAmt = @numTotal / (@numtotalqty  + @numBillQty)  
end


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Update Received from Aaadyakumar on 20.09.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

USE [adminv2]
GO

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

--spGdnNonMovingItems '20070101','20080105',5,50,1000,'D','',30          
 /****** Object:  Stored Procedure dbo.spGdnNonMovingItems    Script Date: 18/01/2003 9:45:42 PM ******/              
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
    
------------------------------------------------------              
-- created by  : Hariharan               
-- created date : 13/12/2002              
-- Comments : V3              
--------------------------------------------------------------------------------------              
-- Modified on  : 13/04/2009                
-- Modified by  : Regin T.              
-- Comments   : User is enabled to select more than one godown in the HQ Reports interface.           
--     So this SP is modified to accept a list of Godown IDs as input.           
--    Input argument @intGodownId is modified as @strGodownID.          
-------------------------------------------------------------------------------------- 
--Ref.No.1
-- Modified on  : 31/05/2012                
-- Modified by  : AADYAKUMAR.D.V              
-- Comments     : Added new columns  cost price,current stock        
--------------------------------------------------------------------------------------                
--spGdnNonMovingItems '20120322','20120422', 50,0, 'F','7','',0       
Create PROC spGdnNonMovingItems @strStartDate AS VarChar(10), @strToDate AS VarChar(10),              
@NoOfRecords AS int, @QuantityLimit AS Numeric(18, 3),               
@MoveType AS Char(1) , @strGodownID AS varchar(250), @strBrand as varchar(250) ='',@NoOfBackDays as int=0  AS              
--              
BEGIN              
 set nocount on              
    CREATE TABLE #gdnItemStockStart              
 (              
  GodownId int,              
  itemid int,              
  sdstock numeric(18,2),              
   edstock numeric(18,2),              
   transstock numeric(18,2)             
  )              
              
 CREATE TABLE #gdnItemStockEnd              
 (              
   GodownId int,              
  itemid int,              
  sdstock numeric(18,2),              
  edstock numeric(18,2),              
  transstock numeric(18,2)             
  )              
 CREATE TABLE #gdnItemStockTrans              
 (              
   GodownId int,              
   itemid int,              
   sdstock numeric(18,2),              
   edstock numeric(18,2),              
   transstock numeric(18,2)             
  )              
 CREATE TABLE #gdnItemStock              
 (              
   GodownId int,              
   itemid int,              
   sdstock numeric(18,2),              
   edstock numeric(18,2),              
   transstock numeric(18,2)              
  )              
 declare @strWhere as varchar(250)              
 declare @strSql as nvarchar(4000)              
 declare @strTop as varchar(250)              
 declare @strBrandCondition as varchar(250)             
 declare @dtMaxBillDateforDead as char(8)             
 declare @strGodCond as varchar(250) -- String Godown Condition        
        
  if @strGodownID <> ''        
    set @strGodCond = ' in (' + @strGodownID + ')'        
  else        
    set @strGodCond = ' not in (-1)' -- To get records of all godowns        
        
 -- get starting stock (stock at the start date)              
         
 set @strSql = N'select gsGodownId, vw.gsItemId, sum(transqty * mode),               
     0.0, 0.0  from vwGdnBinCardWithOpening vw              
     WHERE (sDate <''' +                
     @strStartDate + ''' or sdate is null) and gsGodownId'               
     + @strGodCond +   -- + @strWhere +               
     ' group by gsGodownId, vw.gsItemId '              
        
              
 -- insert the starting stock to gdnItemStockStart              
 insert into #gdnItemStockStart  exec sp_Executesql @strSql              
              
 -- Get the ending stock (stock at the end date)              
 set @strSql = N'select gsGodownId, vw.gsItemId, 0.0, sum(transqty * mode),               
     0.0  from vwGdnBinCardWithOpening vw              
     WHERE (sdate <= ''' +               
     @strtodate + ''' or sdate is null) and gsGodownId' +               
     @strGodCond +  -- + @strWhere +               
     'group by gsGodownId, vw.gsItemId'      
               
              
 -- insert ending stock to gdnItemStockEnd              
 insert into #gdnItemStockEnd exec sp_Executesql @strSql              
              
 -- get transaction qty              
 set @strSql = N'select gsGodownId, vw.gsItemId, 0.0,  0.0, sum(TransQty)                
     from vwGdnBinCardWithOpening vw               
     WHERE (sdate >= ''' +                
     @strStartDate + '''and sdate <= ''' +  @strtodate + ''' )               
      and gsGodownId ' + @strGodCond + --@strWhere +               
     ' and (type = ''Despatch To Shop'' OR               
     type = ''Special Despatch'')              
     group by gsGodownId, vw.gsItemId'               
 --print @strSql              
 -- insert transation qty to gdnItemStockTrans 
               
 insert into #gdnItemStockTrans  exec sp_Executesql @strSql              
     --print 'ddddd'           
  -- Then bring starting stock, ending stock and transaction qty to gdnItemStock              
 insert into #gdnItemStock select GodownId, itemid, sum(sdstock), sum(edstock),               
   sum(transstock) from (              
   select GodownId, itemid, sdstock, edstock, transstock               
   from #gdnItemStockStart              
   union all              
   select GodownId, itemid, sdstock, edstock, transstock               
   from #gdnItemStockEnd              
   union all              
   select GodownId, itemid, sdstock, edstock, transstock               
   from #gdnItemStockTrans) a              
   group by GodownId, itemid              
           
 if @MoveType = 'F'               
  begin              
   set @strWhere = ' AND TransStock >= ' +              
      convert(varchar, @QuantityLimit) +               
     ' AND TransStock > 0' +               
     ' ORDER BY TransStock DESC '              
   set @strTop = 'TOP ' + convert(VarChar, @NoOfRecords)              
  end              
 else if @MoveType = 'S'              
  begin              
   if @QuantityLimit = 0               
    begin              
     set @strWhere = ' AND TransStock > 0' +               
       ' ORDER BY TransStock ASC'              
    end               
   else                 
    begin              
     set @strWhere = ' AND TransStock <= ' +               
       convert(varchar, @QuantityLimit) +              
                                          ' AND TransStock > 0' +               
       ' ORDER BY TransStock ASC'              
    end              
   set @strTop = 'TOP ' + convert(VarChar, @NoOfRecords)              
  end              
 else if @MoveType = 'D'              
  begin              
   set @strWhere = ' AND edStock > 0 AND TransStock = 0'              
   set @strTop = ''              
  end               
if @strBrand<>''            
 set @strBrandCondition = ' and i.Brand =''' + @strBrand +''' '            
else            
  set @strBrandCondition=''    
          
--Ref.No.1---START---              
 --set @strSql = N'select vw1.* from(select ' + @strTop + ' s.*, u.unitname, ic.itemcategoryid, ic.CategoryNameDescription,               
 --  vw.ItemDescription, i.brand, i.itemcode               
 --  from aItem i, aItemCategory ic, aunit u, vwItemDescription vw,               
 --  #gdnItemStock s               
 --  where vw.itemid = s.itemid and s.itemid = i.itemid               
 --  and i.ItemCategoryID = ic.ItemCategoryID and               
 --  u.unitid = i.unitsid ' + @strBrandCondition + @strWhere + ')vw1 '  
 
  set @strSql = N'select vw1.* from(select ' + @strTop + ' s.*, u.unitname, ic.itemcategoryid, ic.CategoryNameDescription,               
   vw.ItemDescription, i.brand, i.itemcode,i.itemrate,
   (SELECT gsstock from vwInquirygodownStock where gsitemid=i.itemid and gsgodownid=godownid ) stock                 
   from aItem i, aItemCategory ic, aunit u, vwItemDescription vw,               
   #gdnItemStock s               
   where vw.itemid = s.itemid and s.itemid = i.itemid               
   and i.ItemCategoryID = ic.ItemCategoryID and               
   u.unitid = i.unitsid ' + @strBrandCondition + @strWhere + ')vw1 '          
--Ref.No.1----END----     
     
---Added by: Sreekanth.M.V            
---Purpose : Dead Items whose bill da date less than (Todate-@NoOfDays) are only shown           
           
if @MoveType = 'D'            
begin            
 set @dtMaxBillDateforDead=(select convert(varchar(8),dateadd("d",-@NoOfBackDays,convert(datetime,@strToDate,120)),112))            
            
            
             
 set @strSql=@strSql + 'inner join            
 (            
 select max(vw.maxbilldate) maxbilldate,vw.itemid from (select max(pbhbilldate) maxbilldate,pbditemid itemid from LOspPurchaseBillheader lph             
 inner join LOspPurchaseBillDetail lpd             
 on lph.pbhbillid=lpd.pbdbillid and lph.pbhcancelled=0            
 group by pbditemid            
                   
 union             
        
 select max(lphbilldate) maxbilldate,lpditemid itemid from LOslocalpurchaseheader lph             
 inner join LosLocalPurchaseDetail lpd on            
 lph.lphbillid=lpd.lpdbillid and lph.lphcancelled=0            
 group by lpditemid) vw            
 group by vw.itemid            
 ) vw2 on vw1.itemid=vw2.itemid             
     and vw2.maxbilldate<''' + @dtMaxBillDateforDead + ''''            
            
end            
            
              
print @strSql              
             
 exec sp_executeSql @strSql              
              
 drop table #gdnItemStockStart              
 drop table #gdnItemStockEnd              
 drop table #gdnItemStockTrans              
 drop table #gdnItemStock              
 set nocount off              
end              
              
              
GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:WWI-707595]
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

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

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spULBookInvoice]    Script Date: 11/10/2011 09:26:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--Modified ON                   : 21/08/2003,28/08/2003, 10/10/2003, 18/10/2003, 06/12/2003              
--Modified by                   : Reji Abraham, Hariharan R, Hariharan R              
--Comments                     : Additional table loscallbookingheader,losserviceinvheader  is added  AND modified fields, previous fields are alias names              
--           : given accoutn wise positng              
--    : given advance amount in transaction currency for easy conversions              
-- Modified by Aneesh - description below            
--    AND li.serinvhamount>0   //Commented by  Aneesh AS the invoices with the parts amount are not posting          
---------------------------------------------------------------------------------------------        
--Ref-01        
--Modified ON :- 22/06/2011        
--Modified By :- Benzigar S D        
--Comment     :- Advance paid is greater than invoice amount condition handled. Previously        
--               in this case, against customer posting will not happened          
---------------------------------------------------------------------------------------------       
--<<Ref-02>>    
--Modified ON :- 03/08/2011        
--Modified By :- MANUNADH.U    
--Comment     :- To avoid the foreign key error because of @intJournalDetailID is not incrementing.     
---------------------------------------------------------------------------------------------------    
--<<Ref-03>>    
--Modified ON :- 10/10/2011        
--Modified By :- SHINE DAS    
--Comment     :- Modification done for GST    
---------------------------------------------    
--<<Ref-04>>    
--Modified ON :- 30/10/2011        
--Modified By :- Nidheesh P V    
--Comment     :- Added isnull condition    
---------------------------------------------    
--<<Ref-05>>    
--Modified ON :- 09/11/2011        
--Modified By :- MANUNADH.U    
--Comment     :- While take Advance Amount in Invoice Currency, ServiceTaxAmount and PartsTaxAmount 
--				 should be considered. Otherwise posting will be wrong.       
---------------------------------------------------------------------------------------------------    
--Ref-06          
--Modified ON :- 21/09/2012          
--Modified By :- Benzigar S D          
--Comment     :- Corrected the posting og Cost of Goods account. Previously actual amount posted     
--               in Cost of Goods account was not correct. Actual Value in cost of Good was in
--               Customer currency. Corrected this       
---------------------------------------------------------------------------------------------         

--spULBookInvoice 1,4    
    
CREATE PROCEDURE [dbo].[spULBookInvoice] @intCompanyID AS INT, @intshopid AS INT AS           
BEGIN                
 DECLARE @intSalesAccountID AS INT                
 DECLARE @intCashAccountID AS INT                
 DECLARE @intJournalID AS INT                
 DECLARE @intJournalDetailID AS INT                
 DECLARE @intFinancialID AS INT                
 DECLARE @dtinvoiceDate AS datetime                
 DECLARE @strinvoiceNo AS VARCHAR(50)                
 DECLARE @intinvoiceid AS INT                
 DECLARE @strRemarks AS VARCHAR(250)                
 DECLARE @intCustomerid AS INT                
 DECLARE @intadvanceaccid AS INT                
 DECLARE @intDepartmentID AS INT                
 DECLARE @numadvance AS NUMERIC(18,2)                
 DECLARE @numtotalcostValue AS NUMERIC(18,2)                
 DECLARE @intComCurID AS INT                
 DECLARE @intinventoryaccid AS INT                
 DECLARE @intcostofgoodsaccid AS INT                
 DECLARE @intserviceaccid AS INT                
 DECLARE @numer AS NUMERIC(28,8)                
 DECLARE @dtutime AS datetime                
 DECLARE @numservcost AS NUMERIC(18,2)                
 DECLARE @numpartscost AS NUMERIC(18,2)                
 DECLARE @numinvamount AS NUMERIC(18,2)                
 DECLARE @Depnumer AS NUMERIC(28,8)                
 DECLARE @numRespAmount AS NUMERIC(18, 2)                
 DECLARE @strExRates AS VARCHAR(50)                
 DECLARE @intOtherShopID AS INT                
 DECLARE @intOtherDepId AS INT                
 DECLARE @OtherDebitAcc AS INT        
 --<<Ref-03>> Start     
 DECLARE @intServiceTaxAccID AS INT    
 DECLARE @intPartsOutputTaxAccID AS INT    
 DECLARE @intPartsOutputTaxAccID_Cur AS INT    
 DECLARE @numServiceTaxPerc AS NUMERIC(18,2)    
 DECLARE @numServiceTaxAmount AS NUMERIC(18,2)      
 DECLARE @numRespServiceTaxAmount AS NUMERIC(18,2)           
 DECLARE @numPartsTaxAmount AS NUMERIC(18,2)      
 DECLARE @numRespPartsTaxAmount AS NUMERIC(18,2)     
 DECLARE @numPartsOutputTaxAmount_Cur AS NUMERIC(18,2)             
 --<<Ref-03>> END    
     
 /* 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                
      
  ---<<Ref-03>> START     
  SET @numServiceTaxPerc =0    
  SET @numServiceTaxAmount =0    
  SET @numPartsTaxAmount =0    
  SET @numRespPartsTaxAmount =0    
  ---<<Ref-03>> END    
     
 ---<<Ref-03>> TO GET SERVICE TTAX ACCOUNT ID. START    
   SELECT @intServiceTaxAccID=c.AccountID FROM ashops a INNER JOIN aTaxCategoryMaster b     
   ON a.ServiceTaxCategoryId =b.TaxId INNER JOIN aAccountMaster c     
   ON b.TaxAccountId =c.AccountID WHERE b.TaxAccountable =1 AND a.ShopID =@intshopid    
 ---<<Ref-03>> END     
       
  SET @numTotalcostValue = 0.0                
  SET @numadvance =0.0                
  SET @numservcost = 0.0                
  SET @numinvamount = 0.0                
     
   SELECT @intcomcurid = currencyid FROM acompanymaster WHERE companyid = @intcompanyid                
   SELECT @intcostofgoodsaccid = CostofGoodsid, @intInventoryaccid = inventoryid FROM                 
   apackagesettings WHERE companyid = @intcompanyid SELECT @OtherDebitAcc =otherShopDebitAccId FROM     
   ashops WHERE shopid = @intshopid     
     
   SET @intJournalID = @intJournalID + 1                
          
      DECLARE invcur CURSOR for                 
    SELECT li.serinvhid,li.serinvno,li.serinvhdate,isnull(LI.SERINVhcustomerid,0)serbookhcustomerid,      
      li.serinvhremarks,li.serinvhdepartmentid,li.serinvhservacc,li.serinvhsalesacc,      
      li.serinvhcashacc,li.serinvhcmpexrate,li.serinvhupdatetime,li.serinvhamount,      
      li.serinvhserviceamt,li.serinvhpartsamt,isnull(serbookadvanceamount,0) serbookadvanceamount,      
      isnull(serbookadvanceacc,0) serbookadvanceacc,li.seinvhdepexrate,serinvhexchangerates,       
      serCallBkhCallShopID    
    FROM losserviceinvheader li                   
    LEFT OUTER JOIN  losserviceheader ls ON li.serinvhjobcardid=ls.serinvhid AND       
    li.serinvhshopid = ls.serinvhshopid AND li.serinvhcompanyid=ls.serinvhcompanyid                
    LEFT OUTER JOIN losservicebookingheader bh ON ls.serinvhbookingid = serbookhid                   
    AND ls.serinvhshopid = serbookhshopid   AND ls.serinvhcompanyid = serbookhcompanyid                  
    LEFT OUTER JOIN loscallbookingheader los ON serbookhrefid = los.serCallBkhid AND       
    bh.serbookhcompanyid=los.serCallBkhcompanyid AND bh.serbookhshopid=los.serCallBkhshopid                
    WHERE li.serinvhcancelled =0 AND li.serinvhposted =0 AND li.serinvhcompanyid = @intCompanyID       
    AND li.serinvhshopid = @intshopid                 
   --AND li.serinvhamount>0   //Commented by  Aneesh AS the invoices with the parts amount are not posting              
                 
  OPEN invcur               
    FETCH NEXT FROM invcur INTO @intinvoiceid,@strinvoiceno,@dtinvoicedate,@intcustomerid,      
     @strremarks,@intdepartmentid,@intserviceaccid,@intsalesaccountid,@intCashAccountID,@numer,       
     @dtutime,@numinvamount,@numservcost,@numpartscost,@numadvance,@intadvanceaccid,@Depnumer,      
     @strExRates,@intOtherShopID            
      
   WHILE @@Fetch_status = 0                  
   BEGIN               
      
   SET @numServiceTaxAmount=0    
     SELECT @numServiceTaxAmount=sum(d.serinvdItemTaxAmount) FROM losserviceinvheader h INNER JOIN losinvoicedservicedetails d ON    
     h.serinvhid = d.serinvdinvoiceid AND h.serinvhshopid = d.serinvdshopid AND h.serinvhcompanyid = d.serinvdcompanyid        
     WHERE h.serinvhshopid = @intshopid AND h.serinvhid= @intinvoiceid and isnull(d.serinvdItemTaxAmount,0)<>0    
         
     SET @numPartsTaxAmount=0    
     SELECT  @numPartsTaxAmount=sum(c.repinvdItemTaxAmount) FROM losserviceinvheader h     
     INNER JOIN losinvoicedpartsreplacedetails c ON c.repinvinvoiceid = h.serinvhid WHERE     
     h.serinvhshopid = @intshopid AND h.serinvhid= @intinvoiceid and isnull(c.repinvdItemTaxAmount,0)<>0        
     
      SET @numservcost= @numservcost-isnull(@numServiceTaxAmount,0) --<<Ref-03>>  --Ref-04    
     SET @numpartscost= @numpartscost-isnull(@numPartsTaxAmount,0) --<<Ref-03>>  --Ref-04       
     
      
    --to take financialid FROM afinancialyear table with curfinancialyear=1 --Z hari011211                
      SELECT @intFinancialID = financialid FROM vwfinyearperiod WHERE @dtinvoiceDate between       
      sdate AND edate           
            
      SET @numTotalcostValue = 0.0                 
       IF @intOtherShopID >0                 
     SELECT @intOtherDepId = departmentid FROM ashops WHERE shopid = @intOtherShopID                
       ELSE                
     SELECT @intOtherDepId = 0                
            
      --for cost price                
       SELECT @numTotalcostValue = isnull(sum(repinvdqty * repinvdcostprice),0)                 
       FROM losinvoicedpartsreplacedetails invd                
       WHERE repinvdshopid = @intshopid AND repinvinvoiceid = @intinvoiceid                
     AND repinvcompanyid = @intcompanyid                
       group by repinvcompanyid, repinvdshopid, repinvinvoiceid                
           
     --TO TAKE THE ADVANCE AMOUNT IN INVOICE CURRENCY                
     --<<Ref-05>>-------START
     --  SET @numadvance = isnull(@numservcost,0) + isnull(@numpartscost,0) - isnull(@numinvamount,0)  
     SET @numadvance = ((isnull(@numservcost,0) + isnull(@numServiceTaxAmount,0)) + 
		(isnull(@numpartscost,0) + isnull(@numPartsTaxAmount,0))) - isnull(@numinvamount,0)
     --<<Ref-05>>-------END
       INSERT INTO moaJournalHeader (JournalID, CompanyID, JournalDate,referenceno, remarks,      
     financialID,Type, CurrencyID,chequedate, updatetime)       
       VALUES(@intJournalID,@intCompanyID,@dtinvoicedate,@strinvoiceNo,@strRemarks,@intFinancialID,      
     'SBI', @intcomCurID,@dtinvoicedate, @dtutime)                
                  
     SET @intJournalDetailID = 1                  
                  
   IF @numpartscost>0                 
      BEGIN /* crediting the sales account with the full parts cost */                
     IF @intCashAccountID is not null                
       EXEC spConvertEquiamount @intCashAccountID, 'a', @intSalesAccountID, 'a',                 
       @strExRates, @numpartscost, @numRespAmount OUTPUT, 'a'                
     ELSE                
     BEGIN                 
      IF @intcustomerid is not null AND @intcustomerid >0                
       EXEC spConvertEquiamount @intcustomerid, 'c', @intSalesAccountID, 'a',                 
       @strExRates, @numpartscost, @numRespAmount OUTPUT, 'a'                
      ELSE                
       EXEC spConvertEquiamount @intOtherDepId, 'd', @intSalesAccountID, 'a',                 
       @strExRates, @numpartscost, @numRespAmount OUTPUT, 'a'                 
     END      
                      
     INSERT INTO moaJournalDetails(JournalID,journaldetailID,CompanyID,JournalCrEDit,      
      AccountID, Amount, actualAmount,departmentID,depamount)                
     VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intSalesAccountID,       
      @numpartscost * @numer, @numRespAmount,@intDepartmentID,@numpartscost*@Depnumer)                   
     SET @intJournalDetailID = @intJournalDetailID +1          
       
   --------  EXEC spConvertEquiamount @intCashAccountID, 'a', @intPartsOutputTaxAccID, 'a',                 
   --------  @strExRates, @numPartsTaxAmount, @numRespAmount OUTPUT, 'a'      
       
   --------INSERT INTO moaJournalDetails(JournalID,journaldetailID,CompanyID,JournalCrEDit,      
   -------- AccountID, Amount, actualAmount,departmentID,depamount)                
   --------VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intPartsOutputTaxAccID,       
   -------- @numPartsTaxAmount * @numer, @numRespAmount,@intDepartmentID,@numPartsTaxAmount*@Depnumer)                   
   --------SET @intJournalDetailID = @intJournalDetailID +1        
       
       
    DECLARE splitTax CURSOR FOR         
    
     SELECT tcm.TaxAccountId,sum(c.repinvdItemTaxAmount)     
     FROM losserviceinvheader h INNER JOIN losinvoicedpartsreplacedetails c ON c.repinvinvoiceid = h.serinvhid     
     LEFT JOIN aTaxCategoryMaster tcm ON tcm.TaxId =c.repinvdItemTaxCategory    
      WHERE h.serinvhshopid = @intshopid AND h.serinvhid= @intinvoiceid and isnull(c.repinvdItemTaxAmount,0)<>0    
      GROUP BY tcm.TaxAccountId    
          
    OPEN splitTax           
      FETCH NEXT FROM splitTax INTO @intPartsOutputTaxAccID_Cur,@numPartsOutputTaxAmount_Cur      
           
       WHILE @@Fetch_status = 0        
       BEGIN                
            
      EXEC spConvertEquiamount @intCashAccountID, 'a', @intPartsOutputTaxAccID_Cur, 'a',                 
       @strExRates, @numPartsOutputTaxAmount_Cur, @numRespAmount OUTPUT, 'a'     
         
         INSERT INTO moaJournalDetails(JournalID,journaldetailID,CompanyID,JournalCrEDit,      
        AccountID, Amount, actualAmount,departmentID,depamount)                
       VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intPartsOutputTaxAccID_Cur,       
        @numPartsOutputTaxAmount_Cur * @numer, @numRespAmount,@intDepartmentID,    
        @numPartsOutputTaxAmount_Cur*@Depnumer)                   
       SET @intJournalDetailID = @intJournalDetailID +1       
                 
      FETCH NEXT FROM splitTax INTO @intPartsOutputTaxAccID_Cur,@numPartsOutputTaxAmount_Cur      
      END        
  --      
     CLOSE splitTax        
     DEALLOCATE splitTax       
              
       
  END                
    
   IF @numservcost >0                 
     BEGIN                 
    IF @intCashAccountID is not null                
     BEGIN    
       EXEC spConvertEquiamount @intCashAccountID, 'a', @intserviceaccid, 'a',                 
       @strExRates, @numservcost, @numRespAmount OUTPUT, 'a'      
       ---To get Tax equ amnt  --<<Ref-03>> START    
        EXEC spConvertEquiamount @intCashAccountID, 'a', @intServiceTaxAccID, 'a',                 
        @strExRates, @numServiceTaxAmount, @numRespServiceTaxAmount OUTPUT, 'a'                
         --<<Ref-03>> END    
     END    
    ELSE                
     BEGIN                
      IF @intcustomerid is not null AND @intcustomerid >0                
       BEGIN    
         --EXEC spConvertEquiamount @intcustomerid, 'c', @intserviceaccid, 'a',                 
         --@strExRates, @numservcost, @numRespAmount OUTPUT, 'a'       
         EXEC spConvertEquiamount @intcustomerid, 'c', @intserviceaccid, 'a',                 
         @strExRates, @numservcost, @numRespAmount OUTPUT, 'a'      
         ---To get Tax equ amnt  --<<Ref-03>> START    
         EXEC spConvertEquiamount @intcustomerid, 'c', @intServiceTaxAccID, 'a',                 
         @strExRates, @numServiceTaxAmount, @numRespServiceTaxAmount OUTPUT, 'a'      
          --<<Ref-03>>  END    
       END    
      ELSE            
       BEGIN               
         EXEC spConvertEquiamount @intOtherDepId, 'd', @intserviceaccid, 'a',                 
         @strExRates, @numservcost, @numRespAmount OUTPUT, 'a'         
          ---To get Tax equ amnt   --<<Ref-03>> START    
         EXEC spConvertEquiamount @intOtherDepId, 'd', @intServiceTaxAccID, 'a',                 
         @strExRates, @numServiceTaxAmount, @numRespServiceTaxAmount OUTPUT, 'a'       
          --<<Ref-03>> END    
       END     
     END              
              
         
    /* crediing the service account with the full parts cost */                
     INSERT INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,                 
      JournalCrEDit, AccountID, Amount, actualAmount,departmentID,depamount)                
     VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intserviceaccid,       
      @numservcost * @numer, @numRespAmount,@intDepartmentID,@numservcost*@Depnumer )     
                  
     SET @intJournalDetailID = @intJournalDetailID +1         
      --<<Ref-03>> START    
      if isnull(@numServiceTaxAmount,0)<> 0     
      begin    
      INSERT INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,                 
      JournalCrEDit, AccountID, Amount, actualAmount,departmentID,depamount)                
    VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intServiceTaxAccID,       
      @numServiceTaxAmount * @numer, @numRespServiceTaxAmount,@intDepartmentID,@numServiceTaxAmount*@Depnumer )     
                  
      SET @intJournalDetailID = @intJournalDetailID +1      
     end         
      --<<Ref-03>> END    
               
     END                
   --hari 020320                
   IF  (@intCashAccountID is not null AND @intCashAccountID <>0)                
   BEGIN                 
    IF @numinvamount>0                 
    BEGIN                
    
     -- DEBITING cash                
     INSERT INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,JournalCrEDit,       
      accountid, Amount, actualAmount,departmentID,depamount)                
     VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intcashaccountid,       
      @numinvamount * @numer, @numinvamount,@intDepartmentID,@numinvamount*@Depnumer)                
     SET @intJournalDetailID = @intJournalDetailID +1                
    END                
    -- copied FROM v2                
    ELSE IF @numinvamount < 0                 
    BEGIN                
     -- Credit Cash cash                
     INSERT INTO moaJournalDetails (JournalID,journaldetailID,CompanyID,JournalCrEDit,       
      accountid, Amount, actualAmount,departmentID,depamount)                
     VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 1,@intcashaccountid,       
      abs(@numinvamount) * @numer, abs(@numinvamount),@intDepartmentID,abs(@numinvamount)*@Depnumer)                
     SET @intJournalDetailID = @intJournalDetailID +1                
    END                
   END                
   ELSE                
   BEGIN                
    IF @numinvamount>0                 
    BEGIN                
     IF @intcustomerid is not null AND @intcustomerid >0                
      -- DEBITING customer                
      INSERT INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,                 
       JournalCrEDit, customerid, Amount, actualAmount,departmentID,depamount)                
      VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intcustomerid,       
      @numinvamount * @numer,@numinvamount,@intDepartmentID,@numinvamount*@Depnumer)                
     ELSE                
     BEGIN                
      EXEC spConvertEquiamount @intOtherDepId, 'd', @OtherDebitAcc, 'a',                 
       @strExRates, @numinvamount , @numRespAmount OUTPUT, 'a'                 
      -- DEBITING customer                
      INSERT INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,                 
       JournalCrEDit, accountid, Amount, actualAmount,departmentID,depamount)                
      VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,                 
       @OtherDebitAcc, @numinvamount * @numer, @numRespAmount,                
       @intDepartmentID,@numinvamount*@Depnumer)                
     END        
     SET @intJournalDetailID = @intJournalDetailID +1  --<<Ref-02>>         
     -----------------------------          
     --Ref-01 BEGIN          
    END          
    ELSE          
    BEGIN          
     IF @numinvamount<0          
     BEGIN                
      IF @intcustomerid is not null AND @intcustomerid >0                
       -- Crediting customer (IF advance paid is grater than invoice amount)               
       INSERT INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,                 
        JournalCrEDit, customerid, Amount, actualAmount,departmentID,depamount)                
       VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 1,                 
        @intcustomerid, abs(@numinvamount) * @numer, abs(@numinvamount),                
        @intDepartmentID,abs(@numinvamount)*@Depnumer)                    
     END           
     --Ref-01 END          
     -----------------------------           
     SET @intJournalDetailID = @intJournalDetailID +1               
    END                
   END              
              
   IF @numadvance>0 AND @intadvanceaccid > 0 -- DEBITING advance             
   BEGIN                
    IF @intCashAccountID is not null AND @intCashAccountID >0                
     EXEC spConvertEquiamount @intCashAccountID, 'a', @intadvanceaccid, 'a',                 
     @strExRates, @numadvance, @numRespAmount OUTPUT, 'a'                
    ELSE IF @intCustomerId is not null AND @intCustomerId >0                 
     EXEC spConvertEquiamount @intCustomerId, 'c', @intadvanceaccid, 'a',                 
     @strExRates, @numadvance, @numRespAmount OUTPUT, 'a'                
    ELSE IF @intOtherShopID is not null AND @intOtherShopID >0                
    EXEC spConvertEquiamount @intOtherDepId, 'd', @intadvanceaccid, 'a',                 
     @strExRates, @numadvance, @numRespAmount OUTPUT, 'a'                
                
    INSERT INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,                 
     JournalCrEDit, accountid, Amount, actualAmount,departmentID,depamount)                
    VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,@intadvanceaccid,       
     @numadvance * @numer, @numRespAmount,@intDepartmentID,@numadvance*@Depnumer)                    
    SET @intJournalDetailID = @intJournalDetailID +1                
   END                
                
   IF @numTotalcostValue>0                 
   BEGIN                 
    IF @intCashAccountID is not null                
     EXEC spConvertEquiamount @intCashAccountID, 'a', @intINVentoryAccID, 'a',                 
     @strExRates, @numTotalcostValue, @numRespAmount OUTPUT, 'a'                
    ELSE                 
    BEGIN                
     IF @intCustomerid is not null AND @intCustomerid >0                
      EXEC spConvertEquiamount @intcustomerid, 'c', @intINVentoryAccID, 'a',                 
      @strExRates, @numTotalcostValue, @numRespAmount OUTPUT, 'a'                
     ELSE                
      EXEC spConvertEquiamount @intOtherDepId, 'd', @intINVentoryAccID, 'a',                 
      @strExRates, @numTotalcostValue, @numRespAmount OUTPUT, 'a'                
    END                
    /* crediing the INVENTORY with the full cost Amount */                
    INSERT INTO moaJournalDetails (JournalID, journaldetailID, CompanyID,                 
     JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)                
    VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 1,                 
     @intINVentoryAccID, @numTotalcostValue * @numer , @numRespAmount,                 
     @intDepartmentID, @numTotalcostValue * @Depnumer )                
              SET @intJournalDetailID = @intJournalDetailID +1                
          
    IF @intCashAccountID is not null                
     EXEC spConvertEquiamount @intCashAccountID, 'a', @intcostofgoodsaccid, 'a',                 
      @strExRates, @numTotalcostValue, @numRespAmount OUTPUT, 'a'                
    ELSE                
    BEGIN                
     IF @intCustomerid is not null AND @intCustomerid >0                
      EXEC spConvertEquiamount @intcustomerid, 'c', @intcostofgoodsaccid, 'a',                 
      @strExRates, @numTotalcostValue, @numRespAmount OUTPUT, 'a'                
     ELSE                
      EXEC spConvertEquiamount @intOtherDepId, 'd', @intcostofgoodsaccid, 'a',                 
      @strExRates, @numTotalcostValue, @numRespAmount OUTPUT, 'a'                
    END                
   -- DEBITING THE COST OF GOODS ACCOUNT                
   INSERT INTO moaJournalDetails (JournalID, journaldetailID,CompanyID,                 
    JournalCrEDit, AccountID, Amount, actualAmount,departmentID, depamount)                
   VALUES (@intJournalID, @intjournalDetailID, @intCompanyID, 0,                 
    @intcostofgoodsaccid, @numtotalcostvalue* @numer, @numRespAmount, --@numtotalcostvalue, --Ref-06                                      
    @intDepartmentID, @numTotalcostValue * @Depnumer)            
  END                
               
  /* mark the record AS postED */                
  update losserviceinvheader SET serinvhposted =1       
  WHERE serinvhcompanyid = @intCompanyID AND serinvhshopid = @intshopid AND serinvhid = @intinvoiceid                 
       
  SET @intJournalID = @intJournalID + 1                
                
  FETCH NEXT FROM invcur INTO @intinvoiceid,@strinvoiceno,@dtinvoicedate,@intcustomerid,      
   @strremarks,@intdepartmentid,@intserviceaccid,@intsalesaccountid,@intCashAccountID,@numer,       
   @dtutime,@numinvamount,@numservcost,@numpartscost,@numadvance,@intadvanceaccid,@Depnumer,      
   @strExRates,@intOtherShopID           
 END                
 CLOSE invcur                
 DEALLOCATE invcur                
END                
        
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Update Description(Wings Requirements Delayed Flight Shedule)on 25/09/2012 from AADYAKUMAR.D.V
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

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

USE [adminv2]
GO
    
-----------------------------------------------------------------------    
--Created on  : 08/Oct/2010    
--Created by : Praveen S    
--Comments : For Inserting the Details In Flights    
------------------------------------------------------------------------   
--Ref.No:1   
--Modified on  : 19/09/2012    
--Modified by  : AADYAKUMAR.D.V   
--Comments     : Added new fields   
------------------------------------------------------------------------  
Create PROCEDURE [dbo].[spInsertFlights]    
@flghtopcompanyid INT,    
@flghtid INT,    
@flghtopid INT,    
@flghtno VARCHAR(50),    
@flghtdepday INT,    
@flghtdeptime DATETIME,    
@flghtremarks VARCHAR(250),    
@flghtactive BIT, 
--Ref.No:1---Start---    
@AirlinesName varchar(200) ,  
@TypeofCatering int ,  
@ExpectedNumberOfPassangers int,   
@DelayDuration datetime,  
@userid int,
@VoucherAmount numeric(18,8)
--Ref.No:1---End---       
AS BEGIN    
  SET NOCOUNT ON    
  INSERT INTO Flights(companyid,FlightID,FlightOpid,FlightNo,FlightDepDay,FlightDepTime,Remarks,Active, 
  --Ref.No:1---Start--- 
  AirlinesName,TypeofCatering,ExpectedNumberOfPassangers,DelayDuration,userid,VoucherAmount)    
  --Ref.No:1---end---
  VALUES    
  (@flghtopcompanyid,@flghtid,@flghtopid,@flghtno,@flghtdepday,@flghtdeptime,@flghtremarks,@flghtactive, 
  --Ref.No:1---Start--- 
  @AirlinesName,@TypeofCatering,@ExpectedNumberOfPassangers,@DelayDuration,@userid,@VoucherAmount )  
  --Ref.No:1---end---    
  SET NOCOUNT OFF    
END


GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:Update Description(Wings Requirements Delayed Flight Shedule)on 25/09/2012 from AADYAKUMAR.D.V
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
USE [adminv2]
GO

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

USE [adminv2]
GO
    
------------------------------------------------------------------------    
--Created on  : 08/Oct/2010    
--Created by : Praveen S    
--Comments : For Updating the Details of Flights    
------------------------------------------------------------------------  
--Ref.No:1   
--Modified on  : 19/09/2012    
--Modified by  : AADYAKUMAR.D.V   
--Comments     : Added new fields   
------------------------------------------------------------------------     
Create PROCEDURE [dbo].[spUpdateFlights]    
@flghtopcompanyid INT,    
@flghtid INT,    
@prevflghtopid INT,    
@flghtopid INT,    
@flghtno VARCHAR(50),    
@flghtdepday INT,    
@flghtdeptime DATETIME,    
@flghtremarks VARCHAR(250),    
@flghtactive BIT,  
--Ref.No:1---start--   
@AirlinesName varchar(200) ,  
@TypeofCatering int ,  
@ExpectedNumberOfPassangers int,   
@DelayDuration datetime,  
@userid int, 
@VoucherAmount numeric(18,8)  
--Ref.No:1---end--    
AS BEGIN    
  SET NOCOUNT ON    
  UPDATE Flights    
  SET FlightNo = @flghtno,FlightDepDay = @flghtdepday,    
  FlightDepTime = @flghtdeptime,Remarks=@flghtremarks,Active=@flghtactive,    
  FlightOpid = @flghtopid,  
  --Ref.No:1---start--  
  AirlinesName=@AirlinesName,  
  TypeofCatering=@TypeofCatering,  
  ExpectedNumberOfPassangers=@ExpectedNumberOfPassangers,  
  DelayDuration=@DelayDuration,  
  userid=@userid , 
  VoucherAmount=@VoucherAmount
  --Ref.No:1---end--    
  WHERE FlightOpid = @prevflghtopid AND FlightID = @flghtid AND companyid = @flghtopcompanyid    
  SET NOCOUNT OFF    
END


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

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

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spInventoryForecast]    Script Date: 09/26/2012 16:54:28 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--------------------------------------------------------------------------------                    
-- This stored procedure is going to be useed to generate Inventory Forecast report                    
-- This report model is given by Echocam                    
--------------------------------------------------------------------------------                    
-- Coded By: Regin T.                    
-- Coded On: 16-04-2009      
--Modified By : YOgesh Joe    
--Modified On :12-05-2009                  
--------------------------------------------------------------------------------                    
-- spInventoryForecast 10      -- 6 Months                     
-- spInventoryForecast 100, 1,'',''3,4,5,6,7,8','1,2,3,4,5,6,7,8,9' -- 100 Days                    
/*                    
User may select one of the below options                    
Parameter: Stock Out in                     
 Next 3 months (A)                    
 Next 6 months (A)                    
 Next 9 months (A)                    
 Next 12 months (A)                    
 No of Days (A)                    
*/   
--------------------------------------------------------------------------------                    
--RefNo-1
--Modified by : Bijesh.B
--Modified on : 19-09-2012
--Ticket id   : YMG-445556 (Fino)
--------------------------------------------------------------------------------                    
--RefNo-2
--Modified by : MANU
--Modified on : 26-09-2012
--Ticket id   : RUU-170152 (Fino)
--Upgrade     : In Inventory Forecast Report,average sale/day is calculated for the last 12 months.
--              In order to customise this, add a date time picker in the report interface to select the date
--              to calculate the average sale/day for that particular date from the package date. 
--------------------------------------------------------------------------------                 
CREATE proc [dbo].[spInventoryForecast]                     
	@intDuration        as int,  -- the number of months/days. e.g. 3 if user selects Stock Out In 3 Months                    
	@bitDurationInDays  as int = 0, -- 1 if duration is in days, 0 if duration is in months                    
	@strDepartmentId as varchar(50),      
	@strCategoryId as varchar(50),
	@strForecastFrom as varchar(10)     --<<RefNo-2>> 
as                    
begin  -- procedure begins                    
                    
	set nocount on                     
	declare @ItemId as nvarchar(2000),@GodownId as nvarchar(2000),@ShopId as nvarchar(2000),      
			@strSQL as nvarchar(2000)                    
	declare @dtPackageDate as datetime                    
	declare @intNoOfSaleDays as int                      
	declare @intDays1 as int                      
	declare @intDays2 as int -- Stores the days inbetween the reporting date and the selected future date                    
	declare @intDays3 as int                      
	declare @Monthname1 as varchar(10),@Monthname2 as varchar(10),@Monthname3 as varchar(10),                
			@Monthname4 as varchar(10),@Monthname5 as varchar(10),@Monthname6 as varchar(10),                
			@Monthname7 as varchar(10),@Monthname8 as varchar(10),@Monthname9 as varchar(10),                
			@Monthname10 as varchar(10),@Monthname11 as varchar(10),@Monthname12 as varchar(10),                
			@BeforeSelected as varchar(25),@Selected as varchar(25),@AfterSelected as varchar(25),              
			@DayORMonth as varchar(10),@dtForecastFrom as datetime     --<<RefNo-2>>               
              
	-- Below variables store the beginning day of the respective months                     
	declare @dtMonthCurrent as datetime,@dtMonthOne     as datetime,@dtMonthTwo     as datetime,                    
			@dtMonthThree   as datetime,@dtMonthFour    as datetime,@dtMonthFive    as datetime,                    
			@dtMonthSix     as datetime,@dtMonthSeven   as datetime,@dtMonthEight   as datetime,                    
			@dtMonthNine    as datetime,@dtMonthTen     as datetime,@dtMonthEleven  as datetime,                    
			@dtMonthTwelve  as datetime                    
                    
	create table #CurrentStock	(                    
									csItemID int,  -- Current Stock Item ID                    
									csStock  numeric(18,2)
								)-- Current Stock Stock                     
	create table #OrderedItems	(                    
									oiItemID     int,  -- Ordered Items Item ID                    
									oiOrderedQty numeric(18,2)
								)                      
	create table #AverageSale	(                    
									asItemID     int,                     
									asAvgSaleQty numeric(18,2)
								)
	create table #MonthSale1	(                   
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale2	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale3	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale4	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale5	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale6	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale7	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale8	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale9	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale10	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale11	(                    
									msItemID  int,                     
									msSaleQty numeric(18,2)
								)                    
	create table #MonthSale12	(                    
									msItemID  int,               
									msSaleQty numeric(18,2)
								)
	select @dtPackageDate = PackageDate from aPackageSettings                    
                    
	-- I. Getting the total stock in all locations of the company  -- Starts        
	create table #ItemIdTable	(	ItemId int	)      
	create table #ShopIdTable	(	ShopId int	)      
	create table #GodownIdTable	(   GodownId int	)      
	create table #DepartmentIdTable	(	DepartmentID int	)      
	
	set @dtForecastFrom = convert(datetime,@strForecastFrom,101)--<<RefNo-2>>

	if @strCategoryId<>''      
		begin      
			set @strSQL=N'      
			insert into #ItemIdTable      
			select ItemId from aitem where ItemCategoryID in ('+ @strCategoryId +')'      
			exec sp_executesql @strSQL      
		end      
	else      
		begin      
			insert into #ItemIdTable select ItemId from aitem       
		end      
      
	if @strDepartmentId<>''       
		begin      
			set @strSQL=N'      
			insert into #ShopIdTable       
			select ShopID from ashops where DepartmentID in('+ @strDepartmentId +')'       
			exec sp_executesql @strSQL      
   
			set @strSQL=N'      
			insert into #GodownIdTable      
			select GodownID from aGodown where DepartmentID in('+ @strDepartmentId +')'             
			exec sp_executesql @strSQL      
       
			set @strSQL=N'      
			insert into #DepartmentIdTable      
			select DepartmentID from adepartmentmaster where DepartmentID in('+@strDepartmentId+')'      
			exec sp_executesql @strSQL      
		end      
	else      
		begin      
			insert into #ShopIdTable select ShopID from ashops      
			insert into #GodownIdTable select GodownID from aGodown      
			insert into #DepartmentIdTable select DepartmentID from adepartmentmaster      
		end      
    
	insert into #CurrentStock                    
		select ItemID, sum(stock) Stock                    
		from             
		(	-- All Shop Stocks           
			select s.itemid ItemID, s.shopid LocationID, sum(s.stock) as Stock                     
			from  vwInquiryShopStock s        
			where s.itemid in (select * from #ItemIdTable)      
				and  s.shopid in(select * from #ShopIdTable)                
			GROUP BY s.shopid, s.itemid                    
                    
			union all                    
                    
			-- All Godown Stocks                    
			select gsitemid ItemID, gsGodownid LocationID, sum(gsstock) as Stock                    
			from vwInquiryGodownStock g      
			where g.gsitemid in (select * from #ItemIdTable)      
				and  g.gsGodownid in(select * from #GodownIdTable)             
			GROUP BY gsitemid, gsgodownid                    
		)a 
		group by ItemID                    
                  
		-- I. Getting the total stock in all locations of the company  -- Ends                     
        -- II. Finding the Purchase Ordered Quantities  -- Starts                     
                    
	insert into #OrderedItems                    
		select              
			podItemID, sum(podQty*Quantity) OrderedItemQty                     
		from      
			loPurchaseOrderHeader                     
			left outer join loPurchaseOrderDetail on  pohPoid=podPoid      
			left outer join aItem i on i.ItemID = podItemID                     
			left outer join aPackingTypeCapacityDetail c                     
			on c.PackingTypeID = podPackingTypeID and c.UnitsID = i.UnitsID                    
		where	  
			podPOID in	(
							select pohPOID from loPurchaseOrderHeader                     
							where pohbillgenerated=0 and pohpoid<>0 and pohcompanyid=1                     
								and pohcancel=0 AND left(pohtype,1)='P' and pohpoonhold = 0
						)      
			and podItemID in (select * from #ItemIdTable)      
			and pohDepartmentid in (select * from #DepartmentIdTable)      
			group by podItemID      
	-- II. Finding the Purchase Ordered Quantities  -- Ends                    
	-- III. Calculating the sale in the last 12 months -- Starts --                    
	-- Beginning of the current month                    
	set @dtMonthCurrent = dateadd("m", 0, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
               
	-- Beginning of of 1st previous month                    
	set @dtMonthOne = dateadd("m", -1, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
                    
	-- Beginning of the 2nd previous month                    
	set @dtMonthTwo = dateadd("m", -2, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
                    
	-- Beginning of the 3rd previous month                    
	set @dtMonthThree = dateadd("m", -3, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 4th previous month                    
	set @dtMonthFour =  dateadd("m", -4, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 5th previous month                    
	set @dtMonthFive = dateadd("m", -5, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 6th previous month                    
	set @dtMonthSix = dateadd("m", -6, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
                    
	-- Beginning of the 7th previous month                    
	set @dtMonthSeven = dateadd("m", -7, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 8th previous month                    
	set @dtMonthEight = dateadd("m", -8, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))          
	                    
	-- Beginning of the 9th previous month                    
	set @dtMonthNine = dateadd("m", -9, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 10th previous month                    
	set @dtMonthTen = dateadd("m", -10, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 11th previous month                    
	set @dtMonthEleven = dateadd("m", -11, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
	                    
	-- Beginning of the 12th previous month                    
	set @dtMonthTwelve = dateadd("m", -12, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                    
                    
	-- Sale in the 1st previous month                    
	insert into #MonthSale1                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                 
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthOne and poshBilldate < @dtMonthCurrent       
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                 
		group by posdItemID                    
	-- Sale in the 2nd previous month                    
	insert into #MonthSale2                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthTwo and poshBilldate < @dtMonthOne       
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                 
			group by posdItemID                   
                    
	-- Sale in the 3rd previous month                    
	insert into #MonthSale3                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthThree and poshBilldate < @dtMonthTwo       
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                   
		group by posdItemID      
                   
	-- Sale in the 4th previous month                   
	insert into #MonthSale4                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthFour and poshBilldate < @dtMonthThree                    
		and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)       
		group by posdItemID   
	                 
	-- Sale in the 5th previous month                    
	insert into #MonthSale5                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthFive and poshBilldate < @dtMonthFour                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)       
		group by posdItemID      
                  
	-- Sale in the 6th previous month                    
	insert into #MonthSale6                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthSix and poshBilldate < @dtMonthFive                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)       
		group by posdItemID      
                               
	-- Sale in the 7th previous month                    
	insert into #MonthSale7             
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthSeven and poshBilldate < @dtMonthSix       
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                    
		group by posdItemID                    
                       
	-- Sale in the 8th previous month                    
	insert into #MonthSale8                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales  
		where                    
			poshBilldate >= @dtMonthEight and poshBilldate < @dtMonthSeven                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)         
		group by posdItemID                    
	-- Sale in the 9th previous month                    
	insert into #MonthSale9                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthNine and poshBilldate < @dtMonthEight                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)         
			group by posdItemID                   
	                    
	-- Sale in the 10th previous month                    
	insert into #MonthSale10                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthTen and poshBilldate < @dtMonthNine                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)        
		group by posdItemID                    
	                 
	-- Sale in the 11th previous month                    
	insert into #MonthSale11                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                    
		from vwShopItemSales                     
		where                    
			poshBilldate >= @dtMonthEleven and poshBilldate < @dtMonthTen                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)      
		group by posdItemID 
			
	-- Sale in the 12th previous month                    
	insert into #MonthSale12                    
		select                     
			posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale 
		from vwShopItemSales                
		where                    
			poshBilldate >= @dtMonthTwelve and poshBilldate < @dtMonthEleven                    
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)      
		group by posdItemID      
	                
	-- III. Calculating the sale in the last 12 months -- Ends --                    
    -- IV. Finding Average Sale -- Starts here --                    
	
	--<<RefNo-2>>
	--set @intNoOfSaleDays = datediff("d",@dtMonthTwelve,@dtMonthCurrent)       --Prev code
	set @intNoOfSaleDays = datediff("d",@dtForecastFrom,@dtPackageDate)       --New code
	--<<RefNo-2>>
	             
	--set @intNoOfSaleDays = datediff("d",convert(datetime,@strSaleStartDate),convert(datetime,@strSaleEndDate))                    
	insert into #AverageSale                    
		select                     
			posdItemID ItemID,                     
			case                     
				when @intNoOfSaleDays = 0 then 0                   
				else                      
					convert(numeric(18,2),sum(posdquantity)/@intNoOfSaleDays)                     
			end AvgSale                    
		from vwShopItemSales                     
		where                     
			poshBilldate >= @dtMonthTwelve and poshBilldate < @dtMonthCurrent       
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                   
		group by posdItemID      
		            
	-- IV. Finding Average Sale -- Ends here --                    
                    
	-- V. Counting the days inbetween the reporting date and the future date  -- Starts                    
	if @bitDurationInDays = 1 -- If duration is specified in days                    
		begin                    
			set @intDays1 = @intDuration - 90  -- before 3 months                    
			if @intDays1 < 0 set @intDays1 = 0                    
			set @intDays2 = @intDuration                    
			set @intDays3 = @intDuration + 90  -- after 3 months                    
		end                    
	else                      -- If duration is specified in months                    
		begin                    
			set @intDays1 = datediff("d", @dtPackageDate, dateadd("m", @intDuration-3, @dtPackageDate))                      
			if @intDays1 < 0 set @intDays1 = 0                    
			set @intDays2 = datediff("d", @dtPackageDate, dateadd("m", @intDuration, @dtPackageDate))                      
			set @intDays3 = datediff("d", @dtPackageDate, dateadd("m", @intDuration+3, @dtPackageDate))                      
		end                    
	-- V. Counting the days inbetween the reporting date and the future date  -- Ends                    
	--VI.Making Before,Next and After Periods---Starts--              
	/*
	select @DayOrMonth=case @bitDurationInDays when 1 then 'Days' when 0 then 'Months' end              
	select @Selected='Next'+space(1)+rtrim(ltrim(str(@intDuration)))+space(1)+rtrim(ltrim(@DayOrMonth))              
	if @DayOrMonth='Months'              
		begin              
			if (@intDuration-3) >0              
				begin              
					select @BeforeSelected='Next'+space(1)+ltrim(rtrim(str(@intDuration-3)))+space(1)+@DayOrMonth              
				end              
			else              
				begin              
					select @BeforeSelected='Next'+space(1)+'0'+space(1)+'Months'              
				end              
		end              
	else -- Days              
		begin              
			if (@intDuration-90) >0              
				begin              
					select @BeforeSelected='Next'+space(1)+ltrim(rtrim(str(@intDuration-90)))+space(1)+@DayOrMonth              
				end              
			else              
				begin              
					select @BeforeSelected='Next'+space(1)+'0'+space(1)+'Days'              
				end              
		end              
	if @DayOrMonth='Months'              
		begin              
			select @AfterSelected='Next'+space(1)+rtrim(ltrim(str(@intDuration+3)))+space(1)+rtrim(ltrim(@DayOrMonth))              
		end              
	else              
		begin              
			select @AfterSelected='Next'+space(1)+rtrim(ltrim(str(@intDuration+90)))+space(1)+rtrim(ltrim(@DayOrMonth))              
		end              
	*/
	/*
	select @DayOrMonth=case @bitDurationInDays when 1 then 'D' when 0 then 'M' end              
	select @Selected=rtrim(ltrim(str(@intDuration)))
	if @bitDurationInDays=0 -- Months                  
		begin              
			if (@intDuration-3) >0              
				begin              
					select @BeforeSelected=ltrim(rtrim(str(@intDuration-3)))
				end              
			else              
				begin              
					select @BeforeSelected='0'
				end              
		end              
	else -- Days              
		begin              
			if (@intDuration-90) >0              
				begin              
					select @BeforeSelected=ltrim(rtrim(str(@intDuration-90)))
				end              
			else              
				begin              
					select @BeforeSelected='0'
				end              
		end              
	if @bitDurationInDays=0 -- Months             
		begin              
			select @AfterSelected=rtrim(ltrim(str(@intDuration+3)))
		end           
	else              
		begin              
			select @AfterSelected=rtrim(ltrim(str(@intDuration+90)))
		end              
	*/
	--select @DayOrMonth=case @bitDurationInDays when 1 then 'D' when 0 then 'M' end              
	select @DayOrMonth=''
	select @Selected=convert(varchar,@intDuration)--+' '+@DayOrMonth              
	if @bitDurationInDays=0 -- Months             
		begin              
			if (@intDuration-3) >0              
				begin              
					select @BeforeSelected=convert(varchar,@intDuration-3)+' '+@DayOrMonth              
				end              
			else              
				begin              
					select @BeforeSelected='0 '+@DayOrMonth             
				end              
		end              
	else -- Days              
		begin              
			if (@intDuration-90) >0              
				begin              
					select @BeforeSelected=convert(varchar,@intDuration-90)+' '+@DayOrMonth              
				end              
			else              
				begin              
					select @BeforeSelected='0 '+@DayOrMonth              
				end              
		end              
	if @bitDurationInDays=0 -- Months            
		begin              
			select @AfterSelected=convert(varchar,@intDuration+3)+' '+@DayOrMonth              
		end              
	else              
		begin              
			select @AfterSelected=convert(varchar,@intDuration+90)+' '+@DayOrMonth              
		end              
	--VI.Making Before,Next and After Periods---Ends--                     
	-- VII. Giving output -- Starts --                    
                
	SELECT  
		@Monthname1=substring(upper(DATENAME(month, DATEADD(month, -1, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -1, PAckageDate)),3,2),            
		@Monthname2=substring(upper(DATENAME(month, DATEADD(month, -2, PAckageDate))),1,3) +'-'+  substring(DATENAME(year,DATEADD(month, -2, PAckageDate)),3,2),            
		@Monthname3=substring(upper(DATENAME(month, DATEADD(month, -3, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -3, PAckageDate)),3,2),            
		@Monthname4=substring(upper(DATENAME(month, DATEADD(month, -4, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -4, PAckageDate)),3,2),            
		@Monthname5=substring(upper(DATENAME(month, DATEADD(month, -5, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -5, PAckageDate)),3,2),            
		@Monthname6=substring(upper(DATENAME(month, DATEADD(month, -6, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -6, PAckageDate)),3,2),            
		@Monthname7=substring(upper(DATENAME(month, DATEADD(month, -7, PAckageDate))),1,3) +'-'+  substring(DATENAME(year,DATEADD(month, -7, PAckageDate)),3,2),            
		@Monthname8=substring(upper(DATENAME(month, DATEADD(month, -8, PAckageDate))),1,3) +'-'+  substring(DATENAME(year,DATEADD(month, -8, PAckageDate)),3,2),            
		@Monthname9=substring(upper(DATENAME(month, DATEADD(month, -9, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -9, PAckageDate)),3,2),            
		@Monthname10=substring(upper(DATENAME(month, DATEADD(month, -10, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -10, PAckageDate)),3,2),            
		@Monthname11=substring(upper(DATENAME(month, DATEADD(month, -11, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -11, PAckageDate)),3,2),            
		@Monthname12=substring(upper(DATENAME(month, DATEADD(month, -12, PAckageDate))),1,3)+'-'+  substring(DATENAME(year,DATEADD(month, -12, PAckageDate)),3,2)             
	From aPAckageSettings                
                   
	select                     
		ItemID, ItemCode, ItemDescription, isnull(csStock,0) CurrentStock, isnull(oiOrderedQty,0) OrderedQty,                     
		isnull(csStock,0)+isnull(oiOrderedQty,0) CurrStockAndOrdered,  -- CS+O                    
		isnull(asAvgSaleQty,0) AverageSale,             
		convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays1) BalanceBefore3Months,                     
		convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays2) SufficientBalance,                    
		convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays3) BalanceAfter3Months,                    
		isnull(m12.msSaleQty,0) Month12, -- Oldest months are listed first                    
		isnull(m11.msSaleQty,0) Month11,isnull(m10.msSaleQty,0) Month10,isnull(m9.msSaleQty,0) Month9,                    
		isnull(m8.msSaleQty,0) Month8,isnull(m7.msSaleQty,0) Month7,isnull(m6.msSaleQty,0) Month6,
		isnull(m5.msSaleQty,0) Month5,isnull(m4.msSaleQty,0) Month4,isnull(m3.msSaleQty,0) Month3,                    
		isnull(m2.msSaleQty,0) Month2,isnull(m1.msSaleQty,0) Month1,@Monthname12 Monthname12,            
		@Monthname11 Monthname11,@Monthname10 Monthname10,@Monthname9 Monthname9,              
		@Monthname8 Monthname8,@Monthname7 Monthname7,@Monthname6 Monthname6,@Monthname5 Monthname5,            
		@Monthname4 Monthname4,@Monthname3 Monthname3,@Monthname2 Monthname2,@Monthname1 Monthname1,            
		@Selected Selected,@BeforeSelected BeforeSelected,@AfterSelected AfterSelected   
		--,isnull(csStock,0)+isnull(oiOrderedQty,0)'csStock + oiOrderedQty',
		--isnull(asAvgSaleQty,0)*@intDays2 'asAvgSaleQty * @intDays2', csStock ,oiOrderedQty,asAvgSaleQty, @intDays2    
	/*                    
	,case                    
		when isnull(csStock,0)+isnull(oiOrderedQty,0) >= convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays2) then                    
		'Inventory OK' --If CS+O(Currennt Stock + Ordered Qty) is enough for given period                    
		when isnull(csStock,0)+isnull(oiOrderedQty,0) >= convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays1) then                    
		'Order Soon'  --If CS+O is not enough for the given period'                    
		else                    
		'Order Urgently' --If CS+O is not enough for even half of the given period                    
		end                    
	Suggestion                    
	*/                    
	from                     
		aItem left outer join #CurrentStock on ItemID = csItemID                    
		left outer join #OrderedItems on ItemID = oiItemID                    
		left outer join #AverageSale on ItemID = asItemID                    
		left outer join #MonthSale12 m12 on ItemID = m12.msItemID                    
		left outer join #MonthSale11 m11 on ItemID = m11.msItemID                    
		left outer join #MonthSale10 m10 on ItemID = m10.msItemID                    
		left outer join #MonthSale9 m9 on ItemID = m9.msItemID                    
		left outer join #MonthSale8 m8 on ItemID = m8.msItemID                    
		left outer join #MonthSale7 m7 on ItemID = m7.msItemID                    
		left outer join #MonthSale6 m6 on ItemID = m6.msItemID                    
		left outer join #MonthSale5 m5 on ItemID = m5.msItemID                    
		left outer join #MonthSale4 m4 on ItemID = m4.msItemID                    
		left outer join #MonthSale3 m3 on ItemID = m3.msItemID                    
		left outer join #MonthSale2 m2 on ItemID = m2.msItemID                    
		left outer join #MonthSale1 m1 on ItemID = m1.msItemID                    
	--where                    

	--<<RefNo-2>>OLD CODE IS COMMENTED
	----RefNo-1 start commented and added
	----isnull(csStock,0)+isnull(oiOrderedQty,0) < isnull(asAvgSaleQty,0)*@intDays2 -- if CS+O is less than sufficient stock                    
	--isnull(csStock,0)+isnull(oiOrderedQty,0) > isnull(asAvgSaleQty,0)*@intDays2 -- if CS+O is less than sufficient stock                    
	----RefNo-1 ends
	--<<RefNo-2>>OLD
			
	order by ItemDescription --<RefNo-2<>>
		
	-- VI. Giving output -- Ends --                    
                    
	drop table #CurrentStock                    
	drop table #OrderedItems                    
	drop table #AverageSale                    
	drop table #MonthSale1                    
	drop table #MonthSale2                    
	drop table #MonthSale3                    
	drop table #MonthSale4                    
	drop table #MonthSale5                    
	drop table #MonthSale6                    
	drop table #MonthSale7                    
	drop table #MonthSale8                    
	drop table #MonthSale9                    
	drop table #MonthSale10                    
	drop table #MonthSale11                    
	drop table #MonthSale12                    
	drop table #ItemIdTable    
	drop table #ShopIdTable    
	drop table #GodownIdTable    
	drop table #DepartmentIdTable                    
	set nocount off                    
                    
end -- procedure ends                    
                    
-----------------------------------------------------------------------------------------------------------------                    


GO


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

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

-- Created by  :  Nidheesh P V      
-- Created on  : 15/01/2010       
-- Purpose     : To get weekly report for the Analysis of Item Sales      

--spAnalysisofItemSalesByWeek 0,0,'','20101202','20101202',0,0,0
----------------------------------------------------------------------------  

----------------------------------------------------------------------------  
--Created on                   : 21/04/2012          
--Comments                     : New sp created for sonee (copy of spAnalysisofItemSalesByWeek)
--                               for new report rptAnalysisofItemSalesByWeekGSTSeparately.rpt
-- Tikect id                   : JDJ-400367 (Sonee)
--------------------------------------------------------------------------   
create proc spAnalysisofItemSalesByWeekGSTSeparately 
@Intshopid as int,
@intCategoryId as int,
@strBrand as varchar(100),
@strStartDate as varchar(10),
@strEndDate as varchar(10),
@intItemId as int,
@intGroupByShop as int,
@intWithColorAndSize as int,
@strCustomerIDs as varchar(5000)=''  
as  
begin  
SET NOCOUNT ON  
-------------------  
select distinct posditemid,ItemDescription, 
sum(posdquantity)over(partition by poshBilldate,poshshopid,posditemid)as Quantity,  
poshBilldate,poshshopid,   
datepart(wk,poshBilldate) as No_Week_Year,  
dense_rank() over (order by datepart(wk,poshBilldate)) as No_Week,  
dense_rank() over (order by datepart(wk,poshBilldate)) as WeekName
--'Week ' + convert(varchar(2),dense_rank() over (order by datepart(wk,poshBilldate))) as WeekName  
from adminv2.dbo.vwShopItemSalesGstSeparately 
inner join adminv2.dbo.aitem i on itemid=posditemid
inner join adminv2.dbo.aitemcategory c on c.ItemCategoryID=i.ItemCategoryID
where (poshshopid=@Intshopid or @Intshopid=0) and poshBilldate>=@strStartDate 
and poshBilldate<=@strEndDate and (i.ItemCategoryID=@intCategoryId or @intCategoryId=0)
and (brand=@strBrand or @strBrand='')  and (posditemid=@intItemId or @intItemId=0)
-------------------  
SET NOCOUNT OFF  
end  


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

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

-- Created  by  : venkitesh          
-- Created  on  : 211103          
-- Comments  : Created  from view vwSalesAnalysisByItem          
--                        in order to enable sorting by item code and item description          
--     in the report rptSalesByItemShopWise          
--Modified  on  : 150404          
-- Comments  : Field changed to amount           
-----------------------------------------------------------------------------------------      
--Modified By : Yogesh Joe      
--Modified On : 02-11-2009      
--Purpose :      
-- To correct average cost calculation in Credit invoice of the bonded ware house type shops.          
-------------------------------------------------------------------------------------------------------------------          
--Modified on                  : 07/08/2010          
--Modified by                  : Sreejith G A          
--Comments                     : Added an additional field Actual Sales Value     
------------------------------------------------------------------------------------------------  
--Modified on                  : 12/08/2010          
--Modified by                  : VinothMurugan V         
--Comments                     : Added poshbillno  
--------------------------------------------------------------------------   
--Modified on                  : 17/11/2010          
--Modified by                  : Abhishek CS        
--Comments                     : Added customerid  
--------------------------------------------------------------------------   

--------------------------------------------------------------------------   
--Created on                   : 20/04/2012          
--Comments                     : New sp created for sonee (copy of spSalesAnalysisByItem)
--                               for new report rptSalesByItemShopwiseGSTSeparately.rpt
-- Tikect id                   : JDJ-400367 (Sonee)
-- spSalesAnalysisByItemGstSeparately 0,0,'','20081009','20081009',0,0,1
--------------------------------------------------------------------------   
    
CREATE PROCEDURE [dbo].[spSalesAnalysisByItemGstSeparately] (@intShopId as int,           
       @intCategoryId as int,          
       @strBrand as Varchar(100),          
       @strStartDate as Varchar(10),          
       @strEndDate as Varchar(10),          
       @intItemId as int,          
       @intGroupByShop as int,          
       @intWithColorAndSize as int,
       @strCustomerIDs as varchar(5000)=''          
     )AS          
BEGIN          
 Declare @strSql As nVarChar(4000)          
 Declare @strBlankString as nVarChar(2)          
           
 Set NoCount On          
 Set ansi_warnings Off          
           
 -- Char(39) is single quote          
 Set @strBlankString = Char(39) + Char(39)          
          
 Set @strSql = N'SELECT MIN(vs.posdItemId) ItemId, MIN(i.ItemCode) ItemCode,           
 AVG(posdunitprice) UnitPrice ,           
 avg(dunitprice) dUnitPrice,          
 avg(cunitprice) cUnitPrice,          
 SUM(posdquantity) Quantity ,          
 poshBillDate,  poshShopId,           
 SUM(costprice*posdquantity)/SUM(posdquantity) AvgCost, SUM(dcostprice*posdquantity)/SUM(posdquantity) AvgDCost,   SUM(vs.cCostprice*posdquantity)/SUM(posdquantity) AvgCCost,           
 convert(numeric(18,2), sum(posdquantity * vs.costprice)) as CostOfSales,           
 convert(numeric(18,2), sum(posdquantity * vs.dcostprice)) as dCostOfSales,           
 convert(numeric(18,2), sum(posdquantity * vs.ccostprice)) as cCostOfSales,           
 convert(numeric(18,2), sum(amount)) SalesValue,           
 convert(numeric(18,2), sum(damount)) dSalesValue,           
 convert(numeric(18,2), sum(camount)) cSalesValue,           
 SUM(posdquantity * vs.costprice) / SUM(posdquantity) AvgCost,           
 convert(numeric(18,2), SUM(posdquantity * vs.costprice)) AS CostOfSales,        
 SUM(amount) SalesValue,    
 convert(numeric(18,2), sum(Actualamount)) ActualSalesValue,           
 convert(numeric(18,2), sum(dActualamount)) dActualSalesValue,           
 convert(numeric(18,2), sum(cActualamount)) cActualSalesValue,          
 i.ItemDescription, MIN(ic.ItemCategoryId) ItemCategoryId,           
 MIN(CategoryNameDescription) CategoryNameDescription  ,           
 ISNULL(MIN(ColorName), ' + @strBlankString + ') ColorName,           
 ISNULL(MIN(SizeName), ' + @strBlankString + ') SizeName,           
 i.ItemDescription ItemDesc, MIN(UnitCode) UnitCode, MIN(Brand) Brand,          
 MIN(s.ShopName) ShopName,poshbillno,poshcustomerid,
 convert(numeric(18,2), sum(GSTAmount)) GSTAmount,           
 convert(numeric(18,2), sum(dGSTAmount)) dGSTAmount,           
 convert(numeric(18,2), sum(cGSTAmount)) cGSTAmount
 FROM vwShopItemSalesGstSeparately vs,           
 aitemcategory ic, aitem i LEFT OUTER JOIN acolor c           
 ON i.colorid = c.colorid LEFT OUTER JOIN asize z           
 ON i.sizeid=z.sizeid, aUnit u, aShops s          
 WHERE vs.posditemid = i.itemid           
 AND i.ItemCategoryId = ic.ItemCategoryId           
 AND i.UnitsId = u.UnitId          
 AND vs.poshShopId = s.ShopId          
 AND vs.PoshBillDate BETWEEN ' + Char(39) + @strStartDate + Char(39) +          
 ' AND '  + Char(39) + @strEndDate + Char(39)          
           
 If @intShopId <> 0           
 Begin          
  Set @strSql = @strSql + ' AND vs.poshShopId = '           
    + CONVERT(Varchar(3), @intShopId)          
 End          
          
 If @intCategoryId <> 0           
 Begin          
  Set @strSql = @strSql + ' AND i.ItemCategoryId = '           
    + CONVERT(Varchar(3), @intCategoryId)          
 End          
          
 If @strBrand <> ''          
 Begin          
  Set @strSql = @strSql + ' AND i.Brand = ' + Char(39) + @strBrand + Char(39)          
 End          
          
 If @intItemId <> 0           
 Begin          
  Set @strSql = @strSql + ' AND vs.posdItemId = '           
    + CONVERT(Varchar(9), @intItemId)          
 End     
if ltrim(rtrim(@strCustomerIDs))<>''
set @strSql = @strSql + ' AND vs. poshcustomerid  ' + @strCustomerIDs  
 
          
 -- set group by clause          
          
 If @intWithColorAndSize = 1           
 Begin          
  If @intGroupByShop = 0           
  Begin          
   Set @strSql = @strSql + ' GROUP BY posdItemId, i.ItemCode, i.ItemDescription,           
   ColorName, SizeName, Type,poshBillDate,  poshShopId,poshbillno,poshcustomerid'          
  End          
  Else          
  Begin          
   Set @strSql = @strSql + ' GROUP BY ShopId, posdItemId,           
   i.ItemCode, i.ItemDescription,           
   ColorName, SizeName, Type,poshBillDate,  poshShopId,poshbillno,poshcustomerid'          
  End          
 End          
 Else --  show without size and color          
 Begin          
  If @intGroupByShop = 0           
  Begin          
   Set @strSql = @strSql + ' GROUP BY i.ItemDescription, Type,poshBillDate,  poshShopId,poshbillno,poshcustomerid'           
  End          
  Else          
  Begin          
   Set @strSql = @strSql + ' GROUP BY ShopId, i.ItemDescription, Type,poshBillDate,  poshShopId,poshbillno,poshcustomerid'          
  End          
 End            
           
print @strSql           
 Exec sp_ExecuteSql @strSql          
               
    
 Set NoCount Off          
 Set ansi_warnings On          
End 

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

/****** Object:  StoredProcedure [dbo].[spInventoryForecast]    Script Date: 10/05/2012 16:19:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spInventoryForecast]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spInventoryForecast]
GO

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spInventoryForecast]    Script Date: 10/05/2012 16:19:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

  
--------------------------------------------------------------------------------                      
-- This stored procedure is going to be useed to generate Inventory Forecast report                      
-- This report model is given by Echocam                      
--------------------------------------------------------------------------------                      
-- Coded By: Regin T.                      
-- Coded On: 16-04-2009        
--Modified By : YOgesh Joe      
--Modified On :12-05-2009                    
--------------------------------------------------------------------------------                      
-- spInventoryForecast 10      -- 6 Months                       
-- spInventoryForecast 100, 1,'',''3,4,5,6,7,8','1,2,3,4,5,6,7,8,9' -- 100 Days                      
/*                      
User may select one of the below options                      
Parameter: Stock Out in                       
 Next 3 months (A)                      
 Next 6 months (A)                      
 Next 9 months (A)                      
 Next 12 months (A)                      
 No of Days (A)                      
*/     
--------------------------------------------------------------------------------                      
--RefNo-1  
--Modified by : Bijesh.B  
--Modified on : 19-09-2012  
--Ticket id   : YMG-445556 (Fino)  
--------------------------------------------------------------------------------                      
--RefNo-2  
--Modified by : MANU  
--Modified on : 26-09-2012  
--Ticket id   : RUU-170152 (Fino)  
--Upgrade     : In Inventory Forecast Report,average sale/day is calculated for the last 12 months.  
--              In order to customise this, add a date time picker in the report interface to select the date  
--              to calculate the average sale/day for that particular date from the package date. 
--				Also the report is taken from current packgedate. Previously the Ist month is taken 
--				as the previous month of Package date. But now onwards Ist month will taken from the
--				current moth of Package date and so on.. 
--spInventoryForecast 6,0,1,35,20120804
--------------------------------------------------------------------------------                   
CREATE proc [dbo].[spInventoryForecast]                       
	@intDuration        as int,  -- the number of months/days. e.g. 3 if user selects Stock Out In 3 Months                      
	@bitDurationInDays  as int = 0, -- 1 if duration is in days, 0 if duration is in months                      
	@strDepartmentId as varchar(50),        
	@strCategoryId as varchar(50),  
	@strForecastFrom as varchar(10)     --<<RefNo-2>>   
as                      
begin  -- procedure begins                      
	set nocount on                       
	declare @ItemId as nvarchar(2000),@GodownId as nvarchar(2000),@ShopId as nvarchar(2000),        
		@strSQL as nvarchar(2000)                      
	declare @dtPackageDate as datetime                      
	declare @intNoOfSaleDays as int                        
	declare @intDays1 as int                        
	declare @intDays2 as int -- Stores the days inbetween the reporting date and the selected future date                      
	declare @intDays3 as int                        
	declare @Monthname1 as varchar(10),@Monthname2 as varchar(10),@Monthname3 as varchar(10),                  
		@Monthname4 as varchar(10),@Monthname5 as varchar(10),@Monthname6 as varchar(10),                  
		@Monthname7 as varchar(10),@Monthname8 as varchar(10),@Monthname9 as varchar(10),                  
		@Monthname10 as varchar(10),@Monthname11 as varchar(10),@Monthname12 as varchar(10),                  
		@BeforeSelected as varchar(25),@Selected as varchar(25),@AfterSelected as varchar(25),                
		@DayORMonth as varchar(10),@dtForecastFrom as datetime     --<<RefNo-2>>                 
                
	-- Below variables store the beginning day of the respective months                       
	declare @dtMonthCurrent as datetime,@dtMonthOne     as datetime,@dtMonthTwo     as datetime,                      
		@dtMonthThree   as datetime,@dtMonthFour    as datetime,@dtMonthFive    as datetime,                      
		@dtMonthSix     as datetime,@dtMonthSeven   as datetime,@dtMonthEight   as datetime,                      
		@dtMonthNine    as datetime,@dtMonthTen     as datetime,@dtMonthEleven  as datetime,                      
		@dtMonthTwelve  as datetime                      
                  
	create table #CurrentStock (                      
         csItemID int,  -- Current Stock Item ID                      
         csStock  numeric(18,2)  
        )-- Current Stock Stock                       
	create table #OrderedItems (                      
         oiItemID     int,  -- Ordered Items Item ID                      
         oiOrderedQty numeric(18,2)  
        )                        
	create table #AverageSale (                      
         asItemID     int,                       
         asAvgSaleQty numeric(18,2)  
        )  
	create table #MonthSale1 (                     
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
	create table #MonthSale2 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
	create table #MonthSale3 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
	create table #MonthSale4 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
	create table #MonthSale5 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
	create table #MonthSale6 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
	create table #MonthSale7 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
	create table #MonthSale8 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
	create table #MonthSale9 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
	create table #MonthSale10 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
	create table #MonthSale11 (                      
         msItemID  int,                       
         msSaleQty numeric(18,2)  
        )                      
	create table #MonthSale12 (                      
         msItemID  int,                 
         msSaleQty numeric(18,2)  
        )  
	select @dtPackageDate = PackageDate from aPackageSettings                      
                      
	-- I. Getting the total stock in all locations of the company  -- Starts          
	create table #ItemIdTable ( ItemId int )        
	create table #ShopIdTable ( ShopId int )        
	create table #GodownIdTable (   GodownId int )        
	create table #DepartmentIdTable ( DepartmentID int )        

	set @dtForecastFrom = convert(datetime,@strForecastFrom,101)--<<RefNo-2>>  
  
	if @strCategoryId<>''        
		begin        
			set @strSQL=N'        
			insert into #ItemIdTable        
			select ItemId from aitem where ItemCategoryID in ('+ @strCategoryId +')'        
			exec sp_executesql @strSQL        
		end        
	else        
		begin        
			insert into #ItemIdTable select ItemId from aitem         
		end        
    
	if @strDepartmentId<>''         
		begin        
			set @strSQL=N'        
			insert into #ShopIdTable         
			select ShopID from ashops where DepartmentID in('+ @strDepartmentId +')'         
			exec sp_executesql @strSQL        

			set @strSQL=N'        
			insert into #GodownIdTable        
			select GodownID from aGodown where DepartmentID in('+ @strDepartmentId +')'               
			exec sp_executesql @strSQL        

			set @strSQL=N'        
			insert into #DepartmentIdTable        
			select DepartmentID from adepartmentmaster where DepartmentID in('+@strDepartmentId+')'        
			exec sp_executesql @strSQL        
		end        
	else        
		begin        
			insert into #ShopIdTable select ShopID from ashops        
			insert into #GodownIdTable select GodownID from aGodown        
			insert into #DepartmentIdTable select DepartmentID from adepartmentmaster        
		end        
  
	insert into #CurrentStock                      
		select ItemID, sum(stock) Stock from ( 
		
		-- All Shop Stocks             
		select s.itemid ItemID, s.shopid LocationID, sum(s.stock) as Stock from  vwInquiryShopStock s          
		where s.itemid in (select * from #ItemIdTable) and  s.shopid in(select * from #ShopIdTable)                  
		GROUP BY s.shopid, s.itemid                      

		union all                      
                  
			-- All Godown Stocks                      
		select gsitemid ItemID, gsGodownid LocationID, sum(gsstock) as Stock from vwInquiryGodownStock g        
		where g.gsitemid in (select * from #ItemIdTable) and  g.gsGodownid in(select * from #GodownIdTable)               
		GROUP BY gsitemid, gsgodownid                      
		)a   
		group by ItemID                      
                    
	-- I. Getting the total stock in all locations of the company  -- Ends                       
    
    -- II. Finding the Purchase Ordered Quantities  -- Starts                       
    insert into #OrderedItems                      
		select podItemID, sum(podQty*Quantity) OrderedItemQty from loPurchaseOrderHeader                       
			left outer join loPurchaseOrderDetail on  pohPoid=podPoid        
			left outer join aItem i on i.ItemID = podItemID                       
			left outer join aPackingTypeCapacityDetail c                       
			on c.PackingTypeID = podPackingTypeID and c.UnitsID = i.UnitsID                      
		where podPOID in (  
		select pohPOID from loPurchaseOrderHeader                       
		where pohbillgenerated=0 and pohpoid<>0 and pohcompanyid=1                       
			and pohcancel=0 AND left(pohtype,1)='P' and pohpoonhold = 0  
		)        
		and podItemID in (select * from #ItemIdTable)        
		and pohDepartmentid in (select * from #DepartmentIdTable)        
		group by podItemID        
	-- II. Finding the Purchase Ordered Quantities  -- Ends                      
 
	-- III. Calculating the sale in the last 12 months -- Starts --                      
			
	--<<RefNo-2>>As on package date                   
	---- Beginning of the current month   
	--set @dtMonthCurrent = dateadd("m", 0, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))                      
    set @dtMonthCurrent = @dtPackageDate --As on package date
    --<<RefNo-2>>
    
    --<<RefNo-2>>       
	---- Beginning of of 1st previous month                      
	--set @dtMonthOne = dateadd("m", -1, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))      
	
	--1st month is taken as Current month of package date   
	--set @dtMonthOne = @dtPackageDate    
	set @dtMonthOne = dateadd("m", 0, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))              
    --<<RefNo-2>>
                      
	-- Beginning of the 2nd previous month      
	--set @dtMonthTwo = dateadd("m", -2, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>> Old                     
	set @dtMonthTwo = dateadd("m", -1, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>>New
	                      
	-- Beginning of the 3rd previous month                      
	--set @dtMonthThree = dateadd("m", -3, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate)) --<<RefNo-2>> Old                      
    set @dtMonthThree = dateadd("m", -2, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>>New                   
    
	-- Beginning of the 4th previous month                      
	--set @dtMonthFour =  dateadd("m", -4, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>> Old                       
    set @dtMonthFour= dateadd("m", -3, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>>New
                     
	-- Beginning of the 5th previous month                      
	--set @dtMonthFive = dateadd("m", -5, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>> Old                       
    set @dtMonthFive= dateadd("m", -4, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>>New
                     
	-- Beginning of the 6th previous month                      
	--set @dtMonthSix = dateadd("m", -6, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>> Old                       
	set @dtMonthSix= dateadd("m", -5, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>>New
	
	-- Beginning of the 7th previous month                      
	--set @dtMonthSeven = dateadd("m", -7, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>> Old                       
    set @dtMonthSeven= dateadd("m", -6, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>>New                   
	
	-- Beginning of the 8th previous month                      
	--set @dtMonthEight = dateadd("m", -8, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>> Old             
    set @dtMonthEight = dateadd("m", -7, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>>New
                 
	-- Beginning of the 9th previous month                      
	--set @dtMonthNine = dateadd("m", -9, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>> Old                       
    set @dtMonthNine = dateadd("m", -8, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>>New
                   
	-- Beginning of the 10th previous month                      
	--set @dtMonthTen = dateadd("m", -10, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>> Old                       
	set @dtMonthTen = dateadd("m", -9, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>>New
	                       
	-- Beginning of the 11th previous month                      
	--set @dtMonthEleven = dateadd("m", -11, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>> Old                       
	set @dtMonthEleven = dateadd("m", -10, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>>New
                   
	-- Beginning of the 12th previous month                      
	--set @dtMonthTwelve = dateadd("m", -12, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>> Old                       
	set @dtMonthTwelve = dateadd("m", -11, dateadd("d",-day(@dtPackageDate)+1,@dtPackageDate))--<<RefNo-2>>New
                  
	-- Sale in the 1st previous month                      
	insert into #MonthSale1                      
		select posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                   
		from vwShopItemSales 
		--<<RefNo-2>>  
		--where poshBilldate >= @dtMonthOne and poshBilldate < @dtMonthCurrent                      
		where poshBilldate >= @dtMonthOne and poshBilldate <= @dtMonthCurrent  
		--<<RefNo-2>>      
			and posdItemID in(select * from #ItemIdTable) and poshShopID in(select * from #ShopIdTable)
		group by posdItemID                      
	
	-- Sale in the 2nd previous month                      
	insert into #MonthSale2                      
		select posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
		from vwShopItemSales                       
		where poshBilldate >= @dtMonthTwo and poshBilldate < @dtMonthOne         
		and posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                   
	group by posdItemID                     
                      
	-- Sale in the 3rd previous month                      
	insert into #MonthSale3                      
		select posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
		from vwShopItemSales                       
		where poshBilldate >= @dtMonthThree and poshBilldate < @dtMonthTwo         
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                     
		group by posdItemID        
                     
	-- Sale in the 4th previous month                     
	insert into #MonthSale4                      
		select posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale from vwShopItemSales                       
		where poshBilldate >= @dtMonthFour and poshBilldate < @dtMonthThree and posdItemID in(
			select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)         
		group by posdItemID     
                    
	-- Sale in the 5th previous month                      
	insert into #MonthSale5                      
		select posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
		from vwShopItemSales 
		where poshBilldate >= @dtMonthFive and poshBilldate < @dtMonthFour                      
			and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)         
		group by posdItemID        
                
	-- Sale in the 6th previous month                      
	insert into #MonthSale6                      
		select posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
		from vwShopItemSales                       
		where poshBilldate >= @dtMonthSix and poshBilldate < @dtMonthFive                      
			and posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)         
		group by posdItemID        
		         
	-- Sale in the 7th previous month                      
	insert into #MonthSale7               
		select posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
		from vwShopItemSales                       
		where poshBilldate >= @dtMonthSeven and poshBilldate < @dtMonthSix         
			and posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                      
		group by posdItemID                      
		 
	-- Sale in the 8th previous month                      
	insert into #MonthSale8                      
		select posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
		from vwShopItemSales    
		where poshBilldate >= @dtMonthEight and poshBilldate < @dtMonthSeven                      
		and  posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)           
		group by posdItemID                      
	
	-- Sale in the 9th previous month                      
	insert into #MonthSale9                      
		select posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
		from vwShopItemSales                       
		where poshBilldate >= @dtMonthNine and poshBilldate < @dtMonthEight                      
			and posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)           
		group by posdItemID                     

	-- Sale in the 10th previous month                      
	insert into #MonthSale10                      
		select posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
		from vwShopItemSales                       
		where poshBilldate >= @dtMonthTen and poshBilldate < @dtMonthNine                      
			and posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)          
		group by posdItemID                      

	-- Sale in the 11th previous month                      
	insert into #MonthSale11                      
		select posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale                      
		from vwShopItemSales                       
		where poshBilldate >= @dtMonthEleven and poshBilldate < @dtMonthTen                      
			and posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)        
		group by posdItemID   

	-- Sale in the 12th previous month                      
	insert into #MonthSale12                      
		select posdItemID ItemID, convert(numeric(18,2),sum(posdquantity)) MonthSale   
		from vwShopItemSales                  
		where poshBilldate >= @dtMonthTwelve and poshBilldate < @dtMonthEleven                      
			and posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)        
		group by posdItemID        
                   
	-- III. Calculating the sale in the last 12 months -- Ends --                      
    -- IV. Finding Average Sale -- Starts here --                      
   
	--<<RefNo-2>>  
	--set @intNoOfSaleDays = datediff("d",@dtMonthTwelve,@dtMonthCurrent)       --Prev code  
	set @intNoOfSaleDays =( datediff("d",@dtForecastFrom,@dtPackageDate) )+1      --New code  
	--<<RefNo-2>>  
                
	--set @intNoOfSaleDays = datediff("d",convert(datetime,@strSaleStartDate),convert(datetime,@strSaleEndDate))                      
 
	insert into #AverageSale                      
		select posdItemID ItemID,case when @intNoOfSaleDays = 0 then 0 else                        
			convert(numeric(18,2),sum(posdquantity)/@intNoOfSaleDays) end AvgSale                      
		from vwShopItemSales      
		--<<RefNo-2>>                 
		--where poshBilldate >= @dtMonthTwelve and poshBilldate < @dtMonthCurrent
		where poshBilldate >= @dtForecastFrom and poshBilldate <= @dtMonthCurrent
		--<<RefNo-2>>   
			and posdItemID in(select * from #ItemIdTable) and poshShopID in (select * from #ShopIdTable)                     
		group by posdItemID        
                
	-- IV. Finding Average Sale -- Ends here --                      
                      
	-- V. Counting the days inbetween the reporting date and the future date  -- Starts                      
	if @bitDurationInDays = 1 -- If duration is specified in days                      
		begin                      
			set @intDays1 = @intDuration - 90  -- before 3 months                      
			
			if @intDays1 < 0 set @intDays1 = 0                      
			
			set @intDays2 = @intDuration                      
			set @intDays3 = @intDuration + 90  -- after 3 months                      
		end                      
	else                      -- If duration is specified in months                      
		begin                      
			set @intDays1 = datediff("d", @dtPackageDate, dateadd("m", @intDuration-3, @dtPackageDate))                        
			if @intDays1 < 0 set @intDays1 = 0                      
			set @intDays2 = datediff("d", @dtPackageDate, dateadd("m", @intDuration, @dtPackageDate))                        
			set @intDays3 = datediff("d", @dtPackageDate, dateadd("m", @intDuration+3, @dtPackageDate))                        
		end                      
	-- V. Counting the days inbetween the reporting date and the future date  -- Ends                      
	
	--VI.Making Before,Next and After Periods---Starts--                
	/*  
	select @DayOrMonth=case @bitDurationInDays when 1 then 'Days' when 0 then 'Months' end                
	select @Selected='Next'+space(1)+rtrim(ltrim(str(@intDuration)))+space(1)+rtrim(ltrim(@DayOrMonth))                
	if @DayOrMonth='Months'                
		begin                
			if (@intDuration-3) >0                
				begin                
					select @BeforeSelected='Next'+space(1)+ltrim(rtrim(str(@intDuration-3)))+space(1)+@DayOrMonth                
				end                
			else                
				begin                
					select @BeforeSelected='Next'+space(1)+'0'+space(1)+'Months'                
				end                
		end                
	else -- Days                
		begin                
			if (@intDuration-90) >0                
				begin                
					select @BeforeSelected='Next'+space(1)+ltrim(rtrim(str(@intDuration-90)))+space(1)+@DayOrMonth                
				end                
			else                
				begin                
					select @BeforeSelected='Next'+space(1)+'0'+space(1)+'Days'                
				end                
		end                
	if @DayOrMonth='Months'                
		begin                
			select @AfterSelected='Next'+space(1)+rtrim(ltrim(str(@intDuration+3)))+space(1)+rtrim(ltrim(@DayOrMonth))                
		end                
	else                
		begin                
			select @AfterSelected='Next'+space(1)+rtrim(ltrim(str(@intDuration+90)))+space(1)+rtrim(ltrim(@DayOrMonth))                
		end                
	*/  
	/*  
	select @DayOrMonth=case @bitDurationInDays when 1 then 'D' when 0 then 'M' end                
	select @Selected=rtrim(ltrim(str(@intDuration)))  
	if @bitDurationInDays=0 -- Months                    
		begin                
			if (@intDuration-3) >0                
				begin                
					select @BeforeSelected=ltrim(rtrim(str(@intDuration-3)))  
				end                
			else                
				begin                
					select @BeforeSelected='0'  
				end                
		end                
	else -- Days                
		begin                
			if (@intDuration-90) >0                
				begin                
					select @BeforeSelected=ltrim(rtrim(str(@intDuration-90)))  
				end                
			else                
				begin			         
					select @BeforeSelected='0'  
				end					   
		end                
	if @bitDurationInDays=0 -- Months               
		begin                
			select @AfterSelected=rtrim(ltrim(str(@intDuration+3)))  
		end             
	else                
		begin                
			select @AfterSelected=rtrim(ltrim(str(@intDuration+90)))  
		end                
	*/  
	--select @DayOrMonth=case @bitDurationInDays when 1 then 'D' when 0 then 'M' end                
	select @DayOrMonth=''  
	select @Selected=convert(varchar,@intDuration)--+' '+@DayOrMonth                
	
	if @bitDurationInDays=0 -- Months               
		begin                
			if (@intDuration-3) >0                
				begin                
					select @BeforeSelected=convert(varchar,@intDuration-3)+' '+@DayOrMonth                
				end                
			else                
				begin                
					select @BeforeSelected='0 '+@DayOrMonth               
				end                
		end                
	else -- Days                
		begin                
			if (@intDuration-90) >0                
				begin                
					select @BeforeSelected=convert(varchar,@intDuration-90)+' '+@DayOrMonth                
				end                
			else                
				begin                
					select @BeforeSelected='0 '+@DayOrMonth                
				end                
		end                
	if @bitDurationInDays=0 -- Months              
		begin                
			select @AfterSelected=convert(varchar,@intDuration+3)+' '+@DayOrMonth                
		end                
	else                
		begin                
			select @AfterSelected=convert(varchar,@intDuration+90)+' '+@DayOrMonth                
		end                
	
	--VI.Making Before,Next and After Periods---Ends--                       
	-- VII. Giving output -- Starts --                      
    
    ----<<RefNo-2>> Old Code is commented below          
	--SELECT 
	--@Monthname1=substring(upper(DATENAME(month,DATEADD(month,-1,PAckageDate))),1,3)+'-'+  
	--	substring(DATENAME(year,DATEADD(month,-1,PAckageDate)),3,2),              
	--@Monthname2=substring(upper(DATENAME(month,DATEADD(month,-2,PAckageDate))),1,3) +'-'+  
	--	substring(DATENAME(year,DATEADD(month, -2, PAckageDate)),3,2),              
	--@Monthname3=substring(upper(DATENAME(month, DATEADD(month, -3, PAckageDate))),1,3)+'-'+  
	--	substring(DATENAME(year,DATEADD(month, -3, PAckageDate)),3,2),              
	--@Monthname4=substring(upper(DATENAME(month, DATEADD(month, -4, PAckageDate))),1,3)+'-'+  
	--	substring(DATENAME(year,DATEADD(month, -4, PAckageDate)),3,2),              
	--@Monthname5=substring(upper(DATENAME(month, DATEADD(month, -5, PAckageDate))),1,3)+'-'+  
	--	substring(DATENAME(year,DATEADD(month, -5, PAckageDate)),3,2),              
	--@Monthname6=substring(upper(DATENAME(month, DATEADD(month, -6, PAckageDate))),1,3)+'-'+  
	--	substring(DATENAME(year,DATEADD(month, -6, PAckageDate)),3,2),              
	--@Monthname7=substring(upper(DATENAME(month, DATEADD(month, -7, PAckageDate))),1,3) +'-'+  
	--	substring(DATENAME(year,DATEADD(month, -7, PAckageDate)),3,2),              
	--@Monthname8=substring(upper(DATENAME(month, DATEADD(month, -8, PAckageDate))),1,3) +'-'+  
	--	substring(DATENAME(year,DATEADD(month, -8, PAckageDate)),3,2),              
	--@Monthname9=substring(upper(DATENAME(month, DATEADD(month, -9, PAckageDate))),1,3)+'-'+  
	--	substring(DATENAME(year,DATEADD(month, -9, PAckageDate)),3,2),              
	--@Monthname10=substring(upper(DATENAME(month, DATEADD(month, -10, PAckageDate))),1,3)+'-'+  
	--	substring(DATENAME(year,DATEADD(month, -10, PAckageDate)),3,2),              
	--@Monthname11=substring(upper(DATENAME(month, DATEADD(month, -11, PAckageDate))),1,3)+'-'+  
	--	substring(DATENAME(year,DATEADD(month, -11, PAckageDate)),3,2),              
	--@Monthname12=substring(upper(DATENAME(month, DATEADD(month, -12, PAckageDate))),1,3)+'-'+  
	--	substring(DATENAME(year,DATEADD(month, -12, PAckageDate)),3,2)               
	--From aPAckageSettings                  
    --<<RefNo-2>>Old
    --<<RefNo-2>>New             
	SELECT 
		@Monthname1=substring(upper(DATENAME(month,DATEADD(month,0,PAckageDate))),1,3)+'-'+  
			substring(DATENAME(year,DATEADD(month,0,PAckageDate)),3,2),              
		@Monthname2=substring(upper(DATENAME(month,DATEADD(month,-1,PAckageDate))),1,3) +'-'+  
			substring(DATENAME(year,DATEADD(month, -1, PAckageDate)),3,2),              
		@Monthname3=substring(upper(DATENAME(month, DATEADD(month, -2, PAckageDate))),1,3)+'-'+  
			substring(DATENAME(year,DATEADD(month, -2, PAckageDate)),3,2),              
		@Monthname4=substring(upper(DATENAME(month, DATEADD(month, -3, PAckageDate))),1,3)+'-'+  
			substring(DATENAME(year,DATEADD(month, -3, PAckageDate)),3,2),              
		@Monthname5=substring(upper(DATENAME(month, DATEADD(month, -4, PAckageDate))),1,3)+'-'+  
			substring(DATENAME(year,DATEADD(month, -4, PAckageDate)),3,2),              
		@Monthname6=substring(upper(DATENAME(month, DATEADD(month, -5, PAckageDate))),1,3)+'-'+  
			substring(DATENAME(year,DATEADD(month, -5, PAckageDate)),3,2),              
		@Monthname7=substring(upper(DATENAME(month, DATEADD(month, -6, PAckageDate))),1,3) +'-'+  
			substring(DATENAME(year,DATEADD(month, -6, PAckageDate)),3,2),              
		@Monthname8=substring(upper(DATENAME(month, DATEADD(month, -7, PAckageDate))),1,3) +'-'+  
			substring(DATENAME(year,DATEADD(month, -7, PAckageDate)),3,2),              
		@Monthname9=substring(upper(DATENAME(month, DATEADD(month, -8, PAckageDate))),1,3)+'-'+  
			substring(DATENAME(year,DATEADD(month, -8, PAckageDate)),3,2),              
		@Monthname10=substring(upper(DATENAME(month, DATEADD(month, -9, PAckageDate))),1,3)+'-'+  
			substring(DATENAME(year,DATEADD(month, -9, PAckageDate)),3,2),              
		@Monthname11=substring(upper(DATENAME(month, DATEADD(month, -10, PAckageDate))),1,3)+'-'+  
			substring(DATENAME(year,DATEADD(month, -10, PAckageDate)),3,2),              
		@Monthname12=substring(upper(DATENAME(month, DATEADD(month, -11, PAckageDate))),1,3)+'-'+  
			substring(DATENAME(year,DATEADD(month, -11, PAckageDate)),3,2)               
	From aPAckageSettings                  
    --<<RefNo-2>>New
    
    select 
		ItemID, ItemCode, ItemDescription, isnull(csStock,0) CurrentStock, 
		isnull(oiOrderedQty,0) OrderedQty,isnull(csStock,0)+isnull(oiOrderedQty,0) CurrStockAndOrdered,  -- CS+O                      
		isnull(asAvgSaleQty,0) AverageSale,               
		convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays1) BalanceBefore3Months,                       
		convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays2) SufficientBalance,                      
		convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays3) BalanceAfter3Months,                      
		isnull(m12.msSaleQty,0) Month12, -- Oldest months are listed first                      
		isnull(m11.msSaleQty,0) Month11,isnull(m10.msSaleQty,0) Month10,isnull(m9.msSaleQty,0) Month9,                      
		isnull(m8.msSaleQty,0) Month8,isnull(m7.msSaleQty,0) Month7,isnull(m6.msSaleQty,0) Month6,  
		isnull(m5.msSaleQty,0) Month5,isnull(m4.msSaleQty,0) Month4,isnull(m3.msSaleQty,0) Month3,                      
		isnull(m2.msSaleQty,0) Month2,isnull(m1.msSaleQty,0) Month1,@Monthname12 Monthname12,              
		@Monthname11 Monthname11,@Monthname10 Monthname10,@Monthname9 Monthname9,                
		@Monthname8 Monthname8,@Monthname7 Monthname7,@Monthname6 Monthname6,@Monthname5 Monthname5,              
		@Monthname4 Monthname4,@Monthname3 Monthname3,@Monthname2 Monthname2,@Monthname1 Monthname1,              
		@Selected Selected,@BeforeSelected BeforeSelected,@AfterSelected AfterSelected     
		--,isnull(csStock,0)+isnull(oiOrderedQty,0)'csStock + oiOrderedQty',  
		--isnull(asAvgSaleQty,0)*@intDays2 'asAvgSaleQty * @intDays2', csStock ,oiOrderedQty,asAvgSaleQty, @intDays2      
		/*                      
		,case                      
		when isnull(csStock,0)+isnull(oiOrderedQty,0) >= convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays2) then                      
		'Inventory OK' --If CS+O(Currennt Stock + Ordered Qty) is enough for given period                      
		when isnull(csStock,0)+isnull(oiOrderedQty,0) >= convert(numeric(18,2), isnull(asAvgSaleQty,0)*@intDays1) then                      
		'Order Soon'  --If CS+O is not enough for the given period'                      
		else                      
		'Order Urgently' --If CS+O is not enough for even half of the given period                      
		end                      
		Suggestion                      
		*/                      
	from aItem 
		left outer join #CurrentStock on ItemID = csItemID                      
		left outer join #OrderedItems on ItemID = oiItemID                      
		left outer join #AverageSale on ItemID = asItemID                      
		left outer join #MonthSale12 m12 on ItemID = m12.msItemID                      
		left outer join #MonthSale11 m11 on ItemID = m11.msItemID                      
		left outer join #MonthSale10 m10 on ItemID = m10.msItemID                      
		left outer join #MonthSale9 m9 on ItemID = m9.msItemID                      
		left outer join #MonthSale8 m8 on ItemID = m8.msItemID                      
		left outer join #MonthSale7 m7 on ItemID = m7.msItemID                      
		left outer join #MonthSale6 m6 on ItemID = m6.msItemID                      
		left outer join #MonthSale5 m5 on ItemID = m5.msItemID                      
		left outer join #MonthSale4 m4 on ItemID = m4.msItemID                      
		left outer join #MonthSale3 m3 on ItemID = m3.msItemID                      
		left outer join #MonthSale2 m2 on ItemID = m2.msItemID                      
		left outer join #MonthSale1 m1 on ItemID = m1.msItemID                      
		--<<RefNo-2>>OLD CODE IS COMMENTED  
		--where and posdItemID in(select * from #ItemIdTable)
		----RefNo-1 start commented and added  
		----isnull(csStock,0)+isnull(oiOrderedQty,0) < isnull(asAvgSaleQty,0)*@intDays2 -- if CS+O is less than sufficient stock                      
		--isnull(csStock,0)+isnull(oiOrderedQty,0) > isnull(asAvgSaleQty,0)*@intDays2 -- if CS+O is less than sufficient stock                      
		----RefNo-1 ends  
		--<<RefNo-2>>OLD  
	where ItemID in(select * from #ItemIdTable)--<<RefNo-2>>New 
	order by ItemDescription --<RefNo-2<>>  
    
    -- VI. Giving output -- Ends --                      
    drop table #CurrentStock                      
	drop table #OrderedItems                      
	drop table #AverageSale                      
	drop table #MonthSale1                      
	drop table #MonthSale2                      
	drop table #MonthSale3                      
	drop table #MonthSale4                      
	drop table #MonthSale5                      
	drop table #MonthSale6                      
	drop table #MonthSale7                      
	drop table #MonthSale8                      
	drop table #MonthSale9                      
	drop table #MonthSale10                      
	drop table #MonthSale11                      
	drop table #MonthSale12                      
	drop table #ItemIdTable      
	drop table #ShopIdTable      
	drop table #GodownIdTable      
	drop table #DepartmentIdTable                      
	set nocount off                      
end -- procedure ends                      
                      
-----------------------------------------------------------------------------------------------------------------                      
  
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:New sp for correcting  tax  problem in sone hardware got from jyothish on 12.10.2012
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO
 USE [adminv2]
GO

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

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spULExchange]    Script Date: 11/16/2011 15:18:00 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
   
    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
    
      
----           
-- Modified on      : 17/07/02          
-- modified by      : leo          
---------------------------------------------------------------------------          
-- Modified on      : 01/01/2002          
-- Modified by      : Kishore          
-- Comments         : Added amount conversion          
-- verified by      : Hariharan          
---------------------------------------------------------------------------          
-- Modified on      : 03/05/2003          
-- Modified by      : R Harikrishnan          
-- Comments         : Corrected the Depexrate          
---------------------------------------------------------------------------          
-- Modified on      : 08/08/2003          
-- Modified by      : Kishore          
-- Comments         : Changed cost price calculation to           
--        incorporate free items concept          
--Verified by      : Hariharan           
--Verified Date     : 03/05/2004 (verified FROM Dev Server(Fies))          
---------------------------------------------------------------------------          
-- Ref 01        
-- Modified on      : 24/09/2011          
-- Modified by      : Shine Das          
-- Comments         : Including GST in Posting        
---------------------------------------------------------------------------          
-- Ref 02        
-- Modified on      : 15/11/2011          
-- Modified by      : Shine Das          
-- Comments         : As per latest information we need to post tax amount only in         
-- OutPut tax account based on scenario. (CREDIT & DEBIT)        
---------------------------------------------------------------------------         
--<<Ref-03>>        
--Modified ON  :- 16/11/2011            
--Modified By  :- MANUNADH.U        
--Comment   :- While credit in to the sales account check whether @numTotalexValue > 0.     
--     :- Otherwise sales account will be posted as zero.    
 --Modified ON  :- 22/11/2011            
--Modified By  :- jyothish
---post group id set in inntory and cost of goods
   
--create  PROCEDURE [dbo].[spULExchange]           
-- @intCompanyId AS INT, @intShopId AS INT           
--AS           
          
--BEGIN            
-- DECLARE @intSalesAccountId AS INT            
-- DECLARE @intCashAccountId AS INT            
-- DECLARE @intJournalID AS INT            
-- DECLARE @intJournalDetailId AS INT            
-- DECLARE @intFinancialID AS INT            
-- DECLARE @dtExDate AS DATETIME            
-- DECLARE @strexNo AS VARCHAR(50)            
-- DECLARE @intCashBankId AS INT            
-- DECLARE @intexid AS INT            
-- DECLARE @strRemarks AS VARCHAR(250)            
-- DECLARE @intDiscountAccountId AS INT            
-- DECLARE @intDepartmentID AS INT            
-- DECLARE @numtotalBillValue AS NUMERIC(18,2)            
-- DECLARE @numtotalexValue AS NUMERIC(18,2)            
-- DECLARE @intComCurId AS INT            
-- DECLARE @intinventoryaccid AS INT            
-- DECLARE @intCostOfGoodsAccId AS INT            
-- DECLARE @intGoodsReturnAccId AS INT            
-- DECLARE @NumEr AS NUMERIC(28,8)            
-- DECLARE @dtutime AS DATETIME            
-- DECLARE @intFailcount AS INT            
-- DECLARE @numNewItemCost AS NUMERIC(18, 3)            
-- DECLARE @numReturnCost AS NUMERIC(18, 3)            
-- DECLARE @strZeroRate AS VARCHAR(1)            
-- DECLARE @NetCost AS NUMERIC (18, 2)            
-- DECLARE @NetSalesValue AS NUMERIC (18, 2)            
------- Ref 01          
-- DECLARE @numBTax AS NUMERIC (18, 2)              
-- DECLARE @numETax AS NUMERIC (18, 2)              
-- DECLARE @numTaxDiff AS NUMERIC (18, 2)              
-- DECLARE @NetSalesWOUTTax AS NUMERIC (18, 2)             
-- DECLARE @intInPutTaxAccount AS INT            
-- DECLARE @numInPutTaxAmount AS NUMERIC (18, 2)             
-- DECLARE @intOutPutTaxAccount AS INT            
-- DECLARE @intOutPutTaxAmount AS NUMERIC (18, 2)             
-- DECLARE @NetSalesValueWTax AS NUMERIC (18, 2)             
-- DECLARE @numtotalBillValueWTax AS NUMERIC(18,2)              
-- DECLARE @numtotalexValueWTax AS NUMERIC(18,2)           
--------- Ref 01          
            
-- DECLARE @numTransEr AS NUMERIC(18, 2),            
--  @numAccEr AS NUMERIC(18, 2),            
--  @numAaccAmt AS NUMERIC(18, 2),            
--  @intCurrencyId AS INT,             
--  @strExRates AS VARCHAR(250),            
--  @NumDepAmt AS NUMERIC(18, 2),             
--  @depExRate AS NUMERIC(28, 8)            
            
-- SET @numTotalBillValue = 0.00            
-- SET @numtotalexvalue = 0.00             
-- SET @numNewitemcost = 0.00             
-- SET @numreturncost = 0.00             
           
-- ------ Ref 01          
--  SET @numtotalBillValueWTax = 0.00              
--  SET @numtotalexValueWTax = 0.00            
--  SET @numBTax = 0.00              
--  SET @numETax = 0.00            
-- -------- Ref 01          
            
-- /* getting the defaults INTO the variables */            
-- SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader  WHERE CompanyId = @intCompanyId            
-- SELECT @intComCurId = CurrencyId FROM aCompanyMaster WHERE CompanyId = @intCompanyId          
-- SELECT @intGoodsReturnAccId = ShopGoodsReturnNoteAccID FROM aShops WHERE ShopId = @intShopId            
            
-- SELECT @intInventoryaccid = InventoryId, @intCostOfGoodsAccId = CostOfGoodsId, @strzerorate = substring(isnull(futurevc, ''), 1, 1)             
-- FROM aPackageSettings WHERE CompanyId = @intCompanyId            
            
-- SET @intJournalID = @intJournalID + 1            
             
-- DECLARE excur CURSOR FOR             
--   SELECT sehExchangeId, sehExchangeNo, sehExchangeDate, sehRemarks, sehSalesAccID,             
--   sehcashaccid, sehexchangerate, updatetime, sehDepartmentID,sehdepexrate, sehexchangerates            
--   FROM losposExchangeHeader             
--   WHERE sehcancelled = 0 and sehposted = 0 and sehCompanyId = @intCompanyId and sehShopId = @intShopId             
            
-- OPEN excur            
--  FETCH NEXT FROM excur INTO @intexid, @strexno, @dtExDate,@strremarks, @intsalesAccountId,           
--  @intCashBankId, @NumEr, @dtutime, @intDepartmentid, @depExRate, @strExRates            
             
-- WHILE @@Fetch_status = 0            
-- BEGIN            
--   -- copied FROM v2            
--   SET @numTotalbillValue = 0.00            
--   SET @numtotalexvalue = 0.00            
--   SET @numNewitemcost = 0.00             
--   SET @numreturncost = 0.00             
            
--   -- FOR converting the amount --->            
--   SELECT @intCurrencyId = CurrencyId FROM aAccountMaster WHERE AccountId = @intcashbankid            
--      EXEC spReturnExRate @intCurrencyId, @strExRates,  @numTransEr output               
            
--   -- to take financialid FROM afinancialyear table with curfinancialyear=1 -- hari011211            
--   SELECT @intFinancialID = financialid FROM vwfinyearperiod WHERE @dtExDate 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 losposExchangeDetail, aItem             
--    WHERE sedExchangeId = @intexid and sedShopId = @intShopId and sedItemId = ItemId             
--    and (sedCostPrice = null or sedCostPrice = 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 hari 011213            
-- BEGIN            
--    -- to update the item rate to the gadCostPrice               
--    update losposExchangeDetail SET sedCostPrice = ItemRate       
--  FROM aItem             
--  WHERE (sedCostPrice = null or sedCostPrice = 0) and             
--  sedExchangeId = @intexid and sedShopId = @intShopId and             
--  sedItemId = ItemId             
            
--    SELECT @numTotalbillValue =  isnull(sum(sedActualUnitPrice  * sedExchangePQty), 0)            
--  FROM losposExchangeDetail            
--  WHERE sedShopId = @intShopId and sedExchangeId  = @intexid            
--  and sedBillOrExchange = 'B' and sedexchangeqty > 0            
--  group by sedShopId, sedExchangeId            
             
--    SELECT @numTotalexValue = isnull(sum(sedActualUnitPrice * sedPQuantity), 0)            
--  FROM losposExchangeDetail            
--  WHERE sedShopId = @intShopId and sedExchangeId = @intexid            
--  and sedBillOrExchange = 'E'            
--  group by sedShopId, sedExchangeId            
              
--    ---- Ref 01          
--       SELECT @numtotalBillValueWTax = isnull(sum(sedunitprice), 0)            
--  FROM losposExchangeDetail              
--  WHERE sedShopId = @intShopId and sedExchangeId  = @intexid              
--  and sedBillOrExchange = 'B' and sedexchangeqty > 0              
--  group by sedShopId, sedExchangeId             
--      set @numtotalexValueWTax=0.00        
--  SELECT @numtotalexValueWTax = isnull(sum(sedunitprice), 0)              
--  FROM losposExchangeDetail              
--  WHERE sedShopId = @intShopId and sedExchangeId = @intexid              
--  and sedBillOrExchange = 'E'              
--  group by sedShopId, sedExchangeId             
--    ---- Ref 01          
            
--  SET @NetSalesValue = abs(@numtotalbillvalue - @numtotalexvalue)            
             
--   --- Ref 01          
--  SET @NetSalesValueWTax  = abs(@numtotalBillValueWTax  - @numtotalexValueWTax )            
            
--  SELECT @numBTax = isnull(sum(sedItemTaxAmount), 0) FROM losposExchangeDetail              
--  WHERE sedShopId = @intShopId and sedExchangeId = @intexid and sedBillOrExchange = 'B' group by sedShopId, sedExchangeId              
                
--  SELECT @numETax = isnull(sum(sedItemTaxAmount), 0) FROM losposExchangeDetail              
--  WHERE sedShopId = @intShopId and sedExchangeId = @intexid and sedBillOrExchange = 'E' group by sedShopId, sedExchangeId             
              
--   --- Ref 01          
               
            
--    SELECT @numreturncost = isnull(sum(sedCostPrice * (sedExchangeQty + isnull(sedExcFreeQty,0))), 0)            
--  FROM losposExchangeDetail            
--  WHERE sedShopId = @intShopId and sedExchangeId  = @intexid            
--  and sedBillOrExchange = 'B' and sedexchangeqty>0            
--  group by sedShopId, sedExchangeId            
              
--    SELECT @numNewitemcost = isnull(sum(sedCostPrice * (sedquantity + isnull(sedFreeQty,0))),0)            
--  FROM losposExchangeDetail            
--  WHERE sedShopId = @intShopId and sedExchangeId  = @intexid            
--  and sedBillOrExchange = 'E'            
--  group by sedShopId, sedExchangeId            
            
--    SET @NetCost = abs(@numreturncost - @numNewitemcost)            
             
--    SET @numTotalbillValue = isnull(@numtotalbillvalue,0)            
--    SET @numtotalexvalue = isnull(@numtotalexvalue,0)            
--    SET @numreturncost = isnull(@numreturncost,0)            
--    SET @numNewitemcost = isnull(@numNewitemcost,0)            
            
--  IF (@numtotalbillvalue <> @numtotalexvalue) or (@numNewitemcost <> @numreturncost)            
-- BEGIN -- to be accounted            
--  INSERT INTO moaJournalHeader (JournalID, CompanyId, JournalDate,             
--   referenceno, remarks,financialID,Type, CurrencyId,chequedate, updatetime)             
--   VALUES             
--   (@intJournalID, @intCompanyId, @dtExDate, @strexNo,             
--   @strRemarks, @intFinancialID, 'EXC', @intComCurId,@dtExDate, @dtutime)            
            
--  SET @intJournalDetailId = 1              
             
--  IF (@numTotalbillValue > @numtotalexvalue) --money out FROM cash box            
--  BEGIN            
                   
--    -- FOR converting the amount --->            
--    SELECT @intCurrencyId = CurrencyId FROM aAccountMaster WHERE AccountId = @intGoodsReturnAccId                  
--    EXEC spReturnExRate @intCurrencyId, @strExRates,@numAccEr output             
--    EXEC spConvertCurrency @numTransEr, @numAccEr,@numTotalbillValue,@numAaccAmt output            
              
--    -- debiting the goods return account            
--    --- Ref 01          
--     INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,             
--  JournalCrEDit, AccountId, Amount, ActualAmount,            
--     DepAmount, departmentID,PostGroup)            
--     VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 0,             
--     @intGoodsReturnAccId, @numTotalbillValue * @NumEr,             
--     @numAaccAmt,             
--     @numTotalbillValue * @depExRate,            
--     @intDepartmentID,null)            
--    SET @intJournalDetailId = @intJournalDetailId + 1           
--    --- Ref 01          
--    --INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,             
--    -- JournalCrEDit, AccountId, Amount, ActualAmount,            
--    -- DepAmount, departmentID)            
--    -- VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 0,             
--    -- @intGoodsReturnAccId, @NetSalesValue * @NumEr,             
--    -- @numAaccAmt,             
--    -- @NetSalesValue * @depExRate,            
--    -- @intDepartmentID)            
--    --SET @intJournalDetailId = @intJournalDetailId + 1            
               
--    -- credit the cash account             
--    --XS          
--    SELECT @intCurrencyId = CurrencyId FROM aAccountMaster WHERE AccountId = @intCashBankId                  
--    EXEC spReturnExRate @intCurrencyId, @strExRates,@numAccEr output             
--    EXEC spConvertCurrency @numTransEr, @numAccEr,@NetSalesValueWTax,@numAaccAmt output            
              
--     EXEC spConvertCurrency @numTransEr, @numAccEr,@NetSalesValueWTax, @numAaccAmt output            
               
--     INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,             
--     JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, departmentID,PostGroup)            
--     VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,             
--     @intCashBankId,  @NetSalesValueWTax * @NumEr,             
--     @numAaccAmt, @NetSalesValueWTax * @depExRate, @intDepartmentID,null )           
               
--    --XE          
--    --INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,             
--    -- JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, departmentID)            
--    -- VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,             
--    -- @intCashBankId,  @NetSalesValue * @NumEr,             
--    -- @NetSalesValue, @NetSalesValue * @depExRate, @intDepartmentID )                 
--    SET @intJournalDetailId = @intJournalDetailId + 1            
              
--     --XS          
               
--    DECLARE exTaxcur CURSOR FOR               
--    -- Ref 02commented        
--     --      SELECT TaxInputAccountId,sedItemTaxAmount FROM losposExchangeDetail,aTaxCategoryMaster                
--     --WHERE sedShopId = @intShopId and sedExchangeId = @intexid and sedBillOrExchange = 'B'   and isnull(sedExchangePQty,0)>0              
--     --and sedItemTaxCategory = TaxId--- and TaxInputAccountId is not null           
             
--    SELECT TaxAccountId,sum(sedItemTaxAmount) sedItemTaxAmount FROM losposExchangeDetail,aTaxCategoryMaster                
--     WHERE sedShopId = @intShopId and sedExchangeId = @intexid and sedBillOrExchange = 'B' and isnull(sedExchangePQty,0)>0              
--     and sedItemTaxCategory = TaxId group by TaxAccountId--- and TaxInputAccountId is not null           
                 
--    OPEN exTaxcur                 
--    FETCH NEXT FROM exTaxcur INTO @intOutPutTaxAccount,@intOutPutTaxAmount            
               
--     WHILE @@Fetch_status = 0              
--     BEGIN                      
--    EXEC spConvertCurrency @numTransEr, @numAccEr,@intOutPutTaxAmount,@numAaccAmt output     -- Ref 02        
                  
--    INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,             
--     JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, departmentID,PostGroup)            
--     VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 0,             
--     --@intInPutTaxAccount,  @numInPutTaxAmount * @NumEr,     -- Ref 02        
--     @intOutPutTaxAccount,  @intOutPutTaxAmount * @NumEr,            
--     @numAaccAmt, @intOutPutTaxAmount * @depExRate, @intDepartmentID,null )           
               
--     SET @intJournalDetailId = @intJournalDetailId + 1            
                  
--      SET @intJournalDetailId = @intJournalDetailId + 1             
--       FETCH NEXT FROM exTaxcur INTO @intOutPutTaxAccount,@intOutPutTaxAmount    -- Ref 02        
--      END              
--  --            
--     Close exTaxcur              
--     Deallocate exTaxcur                   
                
               
--     DECLARE exTaxOUTcur CURSOR FOR               
                 
--     SELECT TaxAccountId,sum(sedItemTaxAmount) sedItemTaxAmount FROM losposExchangeDetail,aTaxCategoryMaster                
--     WHERE sedShopId = @intShopId and sedExchangeId = @intexid and sedBillOrExchange = 'E'             
--     and sedItemTaxCategory = TaxId group by TaxAccountId--- and TaxInputAccountId is not null            
              
--    OPEN exTaxOUTcur              
               
--    FETCH NEXT FROM exTaxOUTcur INTO @intOutPutTaxAccount,@intOutPutTaxAmount            
                 
--    WHILE @@Fetch_status = 0             
--    BEGIN            
                   
--    EXEC spConvertCurrency @numTransEr, @numAccEr,@intOutPutTaxAmount,@numAaccAmt output             
                   
--     INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,               
--     JournalCrEDit, AccountId, Amount, ActualAmount,              
--     DepAmount, departmentID,PostGroup)              
--     VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,               
--     @intOutPutTaxAccount, @intOutPutTaxAmount * @NumEr,               
--     @numAaccAmt,               
--     @intOutPutTaxAmount * @depExRate,              
--     @intDepartmentID,null)             
                    
--    SET @intJournalDetailId = @intJournalDetailId + 1             
--     FETCH NEXT FROM exTaxOUTcur INTO @intOutPutTaxAccount,@intOutPutTaxAmount            
--    END              
--    --            
               
--   Close exTaxOUTcur              
--   Deallocate exTaxOUTcur              
               
--    EXEC spConvertCurrency @numTransEr, @numAccEr,@numTotalexValue,@numAaccAmt output            
--    -- credit the sales account        
--    --<<Ref-03>>       
--    IF @numTotalexValue>0    
--    BEGIN     
--    INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,             
--     JournalCrEDit, AccountId, Amount, actualAmount, DepAmount, departmentID,PostGroup)            
--     VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,             
----     @intSalesAccountId,  @NetSalesValue * @NumEr,             
-- @intSalesAccountId,  @numTotalexValue * @NumEr,@numAAccAmt,@numTotalexValue * @depExRate, @intDepartmentID,null)            
--    SET @intJournalDetailId = @intJournalDetailId + 1            
--    --<<Ref-03>>    
--    END     
--    --XE          
--   END            
-- else            
--   BEGIN            
--    -- debiting the cash account             
--    SELECT @intCurrencyId = CurrencyId FROM aAccountMaster WHERE AccountId = @intCashBankId           
--    EXEC spReturnExRate @intCurrencyId, @strExRates, @numAccEr output             
--    EXEC spConvertCurrency @numTransEr, @numAccEr,@NetSalesValueWTax, @numAaccAmt output           
--     --XS          
--    INSERT INTO moaJournalDetails (JournalId, JournalDetailId, CompanyId,             
--     JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, departmentID,PostGroup)            
--     VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 0,          
--     @intCashBankId, @NetSalesValueWTax * @NumEr ,             
--     @numAaccAmt,             
--     @NetSalesValueWTax * @depExRate, @intDepartmentID,null )            
--            --INSERT INTO moaJournalDetails (JournalId, JournalDetailId, CompanyId,             
--     --JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, departmentID)            
--     --VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 0,             
--     --@intCashBankId, (@numtotalexvalue - @numtotalbillvalue) * @NumEr ,             
--     --@numtotalexvalue - @numtotalbillvalue,             
--     --(@numtotalexvalue - @numtotalbillvalue) * @depExRate, @intDepartmentID )           
--       ---XE          
--    SET @intJournalDetailId = @intJournalDetailId + 1            
              
--     --XS          
--  SELECT @intCurrencyId = CurrencyId FROM aAccountMaster WHERE AccountId = @intGoodsReturnAccId           
--    EXEC spReturnExRate @intCurrencyId, @strExRates, @numAccEr output             
--    EXEC spConvertCurrency @numTransEr, @numAccEr,@numTotalbillValue, @numAaccAmt output           
              
--     INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,             
--     JournalCrEDit, AccountId, Amount, ActualAmount,            
--     DepAmount, departmentID,PostGroup)            
--     VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 0,             
--     @intGoodsReturnAccId, @numTotalbillValue * @NumEr,             
--     @numAaccAmt,             
--     @numTotalbillValue * @depExRate,            
--     @intDepartmentID,null)            
--    SET @intJournalDetailId = @intJournalDetailId + 1           
--    --XE          
              
--    -- FOR converting the amount --->            
--    SELECT @intCurrencyId = CurrencyId FROM aAccountMaster WHERE AccountId = @intSalesAccountId            
--       EXEC spReturnExRate @intCurrencyId, @strExRates, @numAccEr output            
--       EXEC spConvertCurrency @numTransEr, @numAccEr, @numTotalexValue, @numAaccAmt output            
              
--    -- credit the sales account            
--    --XS          
--     INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,             
--     JournalCrEDit, AccountId, Amount, actualAmount, DepAmount, departmentID,PostGroup)            
--     VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,             
--     @intSalesAccountId,  @numTotalexValue * @NumEr,             
--     @numAAccAmt,             
--     @numTotalexValue * @depExRate, @intDepartmentID,null)           
--    --INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,             
--    -- JournalCrEDit, AccountId, Amount, actualAmount, DepAmount, departmentID)            
--    -- VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,             
--    -- @intSalesAccountId,  (@numtotalexvalue - @numtotalbillvalue) * @NumEr,             
--    -- @numAAccAmt,             
--    -- (@numtotalexvalue - @numtotalbillvalue) * @depExRate, @intDepartmentID)            
--       --XE          
--    SET @intJournalDetailId = @intJournalDetailId + 1          
              
--     --XS          
               
--      DECLARE exTaxcur CURSOR FOR               
                 
--         -- Ref 02 Comments        
--     --SELECT TaxInputAccountId,sedItemTaxAmount FROM losposExchangeDetail,aTaxCategoryMaster                
--     --WHERE sedShopId = @intShopId and sedExchangeId = @intexid and sedBillOrExchange = 'B'  and isnull(sedExchangePQty,0)>0               
--     --and sedItemTaxCategory = TaxId--- and TaxInputAccountId is not null           
--          SELECT TaxAccountId,sum(sedItemTaxAmount) sedItemTaxAmount FROM losposExchangeDetail,aTaxCategoryMaster                
--     WHERE sedShopId = @intShopId and sedExchangeId = @intexid and sedBillOrExchange = 'B'  and isnull(sedExchangePQty,0)>0               
--     and sedItemTaxCategory = TaxId group by TaxAccountId--- and TaxInputAccountId is not null            
              
                 
--    OPEN exTaxcur                 
--    FETCH NEXT FROM exTaxcur INTO @intOutPutTaxAccount,@intOutPutTaxAmount    -- Ref 02        
               
--     WHILE @@Fetch_status = 0              
--     BEGIN                      
--    EXEC spConvertCurrency @numTransEr, @numAccEr,@intOutPutTaxAmount,@numAaccAmt output             
                  
--    INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,             
--     JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, departmentID,PostGroup)            
--     VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 0,             
--     --@intInPutTaxAccount,  @numInPutTaxAmount * @NumEr,    -- Ref 02         
--     @intOutPutTaxAccount,  @intOutPutTaxAmount * @NumEr,            
--     @numAaccAmt, @intOutPutTaxAmount * @depExRate, @intDepartmentID,null )           
               
--     SET @intJournalDetailId = @intJournalDetailId + 1            
                  
--      SET @intJournalDetailId = @intJournalDetailId + 1             
--       FETCH NEXT FROM exTaxcur INTO @intOutPutTaxAccount,@intOutPutTaxAmount    -- Ref 02        
--      END              
--  --            
--     Close exTaxcur              
--     Deallocate exTaxcur                   
                
               
--     DECLARE exTaxOUTcur CURSOR FOR               
                 
--     SELECT TaxAccountId,sum(sedItemTaxAmount) sedItemTaxAmount FROM losposExchangeDetail,aTaxCategoryMaster                
--     WHERE sedShopId = @intShopId and sedExchangeId = @intexid and sedBillOrExchange = 'E'             
--     and sedItemTaxCategory = TaxId group by TaxAccountId--- and TaxInputAccountId is not null            
              
--    OPEN exTaxOUTcur              
               
--    FETCH NEXT FROM exTaxOUTcur INTO @intOutPutTaxAccount,@intOutPutTaxAmount            
                 
--    WHILE @@Fetch_status = 0              
--    BEGIN            
                   
--    EXEC spConvertCurrency @numTransEr, @numAccEr,@intOutPutTaxAmount,@numAaccAmt output             
                   
--     INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,               
--     JournalCrEDit, AccountId, Amount, ActualAmount,              
--     DepAmount, departmentID,PostGroup)              
--     VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,               
--     @intOutPutTaxAccount, @intOutPutTaxAmount * @NumEr,               
--     @numAaccAmt,               
--     @intOutPutTaxAmount * @depExRate,              
--     @intDepartmentID,null)             
                    
--    SET @intJournalDetailId = @intJournalDetailId + 1             
--     FETCH NEXT FROM exTaxOUTcur INTO @intOutPutTaxAccount,@intOutPutTaxAmount            
--    END              
--    --            
               
--   Close exTaxOUTcur              
--   Deallocate exTaxOUTcur              
               
--    END                  
            
--    IF @numNewitemcost > @numreturncost            
--    -- debiting inventory value IF the net effect of exchange increases stock value            
--    BEGIN            
             
--     -- FOR CONVERTING AMOUNT --->            
--     SELECT @intCurrencyId = CurrencyId             
--      FROM aAccountMaster            
--      WHERE AccountId = @intINVentoryAccID            
              
--     EXEC spReturnExRate @intCurrencyId, @strExRates,             
--         @numAccEr output             
                 
--     EXEC spConvertCurrency @numTransEr, @numAccEr,             
--       @NetCost,             
--       @numAaccAmt output            
        
            
--     -- crediting inventory value            
--     INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,             
--      JournalCrEDit, AccountId, Amount, actualAmount, DepAmount, departmentID,PostGroup)            
--      VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,             
--      @intInventoryaccid,  @NetCost * @NumEr,             
--      @numAaccAmt,             
--      @NetCost * @DepExRate, @intDepartmentID,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,             
--      @NetCost, @numAaccAmt output            
            
--     -- debiting cost of goods sold account            
--     INSERT INTO moaJournalDetails (JournalID,             
--      JournalDetailId, CompanyId,             
--      JournalCrEDit, AccountId, Amount, actualAmount,             
--      DepAmount, departmentID,PostGroup)            
--      VALUES (@intJournalID, @intJournalDetailId,             
--      @intCompanyId, 0,             
--      @intCostOfGoodsAccId,              
--      @NetCost * @numEr ,             
--      @numAaccAmt,             
--      @NetCost * @depExRate,            
--      @intDepartmentID,4)            
               
--    END            
            
--    IF @numNewitemcost < @numreturncost            
--    -- crediting inventory value IF the net effect of exchange increases stock value            
--    BEGIN            
--     -- FOR CONVERTING AMOUNT --->            
--     SELECT @intCurrencyId = CurrencyId             
--      FROM aAccountMaster            
--      WHERE AccountId = @intINVentoryAccID                
            
--     EXEC spReturnExRate @intCurrencyId, @strExRates, @numAccEr output             
                 
--     EXEC spConvertCurrency @numTransEr, @numAccEr, @NetCost,             
--        @numAaccAmt output            
            
--     -- debiting  inventory account            
--     INSERT INTO moaJournalDetails (JournalId, JournalDetailId, CompanyId,             
--      JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, departmentID,PostGroup)            
--      VALUES (@intJournalId, @intJournalDetailId, @intCompanyId, 0,             
--      @intInventoryaccid,  @NetCost * @numEr,             
--      @numAaccAmt,             
--      @NetCost * @depExRate,            
--      @intDepartmentID,2)            
            
--     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,             
--      @NetCost, @numAaccAmt output            
            
--     -- crediting cost of goods sold account            
--     INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,             
--      JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, DepartmentID,PostGroup)            
--      VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,             
--      @intCostOfGoodsAccId,  @NetCost * @numEr,             
--      @numAaccAmt, @NetCost * @depExRate, @intDepartmentID,2)            
            
--    END            
--   END -- END FOR accounting            
            
--    -- mark the record AS postED             
--   update losposExchangeHeader SET sehpostED =1 WHERE sehCompanyId = @intCompanyId             
--    and sehShopId = @intShopId and sehExchangeId = @intexid              
                
--   SET @intJournalID = @intJournalID + 1            
--   SET @numTotalbillValue = 0.00            
--   SET @numtotalexvalue = 0.00            
--   SET @numNewitemcost = 0.00             
--   SET @numreturncost = 0.00             
--  END -- FOR item rate = 0 check hari 011213            
            
--  FETCH NEXT FROM excur INTO @intexid, @strexno, @dtExDate, @strremarks,             
--   @intsalesAccountId, @intCashBankId, @NumEr, @dtutime, @intDepartmentid,            
--   @depExRate, @strExRates            
-- END            
-- Close excur            
-- Deallocate excur            
--END 


-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------    
  
        
          
            
----                 
-- Modified on      : 10/10/2012                
-- modified by      : jyothish                

-- Comments         :  i have created new sp for correcting    tax  problem       
---------------------------------------------------------------------------       
--spULExchange 1,4
         
create procedure [dbo].[spULExchange]                 
 @intCompanyId AS INT, @intShopId AS INT                 
AS                 
                
BEGIN                  
 DECLARE @intSalesAccountId AS INT                  
 DECLARE @intCashAccountId AS INT                  
 DECLARE @intJournalID AS INT                  
 DECLARE @intJournalDetailId AS INT                  
 DECLARE @intFinancialID AS INT                  
 DECLARE @dtExDate AS DATETIME                  
 DECLARE @strexNo AS VARCHAR(50)                  
 DECLARE @intCashBankId AS INT                  
 DECLARE @intexid AS INT                  
 DECLARE @strRemarks AS VARCHAR(250)                  
 DECLARE @intDiscountAccountId AS INT                  
 DECLARE @intDepartmentID AS INT                  
 DECLARE @numtotalBillValue AS NUMERIC(18,2)                  
 DECLARE @numtotalexValue AS NUMERIC(18,2)                  
 DECLARE @intComCurId AS INT                  
 DECLARE @intinventoryaccid AS INT                  
 DECLARE @intCostOfGoodsAccId AS INT                  
 DECLARE @intGoodsReturnAccId AS INT                  
 DECLARE @NumEr AS NUMERIC(28,8)                  
 DECLARE @dtutime AS DATETIME                  
 DECLARE @intFailcount AS INT            
 DECLARE @numNewItemCost AS NUMERIC(18, 3)                  
 DECLARE @numReturnCost AS NUMERIC(18, 3)                  
 DECLARE @strZeroRate AS VARCHAR(1)                  
 DECLARE @NetCost AS NUMERIC (18, 2)                  
 DECLARE @NetSalesValue AS NUMERIC (18, 2)                  
----- Ref 01                
 DECLARE @numBTax AS NUMERIC (18, 2)                    
 DECLARE @numETax AS NUMERIC (18, 2)                    
 DECLARE @numTaxDiff AS NUMERIC (18, 2)                    
 DECLARE @NetSalesWOUTTax AS NUMERIC (18, 2)          
 DECLARE @intInPutTaxAccount AS INT                  
 DECLARE @numInPutTaxAmount AS NUMERIC (18, 2)                   
 DECLARE @intOutPutTaxAccount AS INT                  
 DECLARE @intOutPutTaxAmount AS NUMERIC (18, 2)                   
 DECLARE @NetSalesValueWTax AS NUMERIC (18, 2)                   
 DECLARE @numtotalBillValueWTax AS NUMERIC(18,2)                    
 DECLARE @numtotalexValueWTax AS NUMERIC(18,2)    
 DECLARE @numtotalExVal AS NUMERIC(18,2)  ---- Ref 04      
 DECLARE @numtTaxExVal AS NUMERIC(18,2)     
 DECLARE @intJournalType AS INT  
 DECLARE  @NetSalesValueWTaxTmp   AS NUMERIC(18,2)
------- Ref 01                
                  
 DECLARE @numTransEr AS NUMERIC(18, 2),                  
  @numAccEr AS NUMERIC(18, 2),                  
  @numAaccAmt AS NUMERIC(18, 2),                  
  @intCurrencyId AS INT,                   
  @strExRates AS VARCHAR(250),                  
  @NumDepAmt AS NUMERIC(18, 2),                   
  @depExRate AS NUMERIC(28, 8)                  
                  
 SET @numTotalBillValue = 0.00                  
 SET @numtotalexvalue = 0.00                   
 SET @numNewitemcost = 0.00                   
 SET @numreturncost = 0.00                   
                 
 ------ Ref 01                
  SET @numtotalBillValueWTax = 0.00                    
  SET @numtotalexValueWTax = 0.00                  
  SET @numBTax = 0.00                    
  SET @numETax = 0.00                  
 SELECT @intJournalID = isnull(max(JournalID),0) FROM moaJournalHeader  WHERE CompanyId = @intCompanyId                  
 SELECT @intComCurId = CurrencyId FROM aCompanyMaster WHERE CompanyId = @intCompanyId                
 SELECT @intGoodsReturnAccId = ShopGoodsReturnNoteAccID FROM aShops WHERE ShopId = @intShopId                  
                  
 SELECT @intInventoryaccid = InventoryId, @intCostOfGoodsAccId = CostOfGoodsId, @strzerorate = substring(isnull(futurevc, ''), 1, 1)                   
 FROM aPackageSettings WHERE CompanyId = @intCompanyId                  
                  
 SET @intJournalID = @intJournalID + 1       
   
     
                    
 DECLARE excur CURSOR FOR                   
   SELECT sehExchangeId, sehExchangeNo, sehExchangeDate, sehRemarks, sehSalesAccID,                   
   sehcashaccid, sehexchangerate, updatetime, sehDepartmentID,sehdepexrate, sehexchangerates                  
   FROM losposExchangeHeader                   
   WHERE sehcancelled = 0 and sehposted = 0 and sehCompanyId = @intCompanyId and sehShopId = @intShopId    
   OPEN excur                  
   FETCH NEXT FROM excur INTO @intexid, @strexno, @dtExDate,@strremarks, @intsalesAccountId,                 
   @intCashBankId, @NumEr, @dtutime, @intDepartmentid, @depExRate, @strExRates                  
                   
  WHILE @@Fetch_status = 0                  
  BEGIN    

        
      SET @numTotalbillValue = 0.00                  
    SET @numtotalexvalue = 0.00                  
    SET @numNewitemcost = 0.00                   
    SET @numreturncost = 0.00            
    set @numtotalBillValueWTax=0.0   
    set @numtTaxExVal=0.0  
    set @NetSalesValueWTax=0.0  
    set    @NetSalesValueWTaxTmp=0.0
    -- FOR converting the amount --->                  
    SELECT @intCurrencyId = CurrencyId FROM aAccountMaster WHERE AccountId = @intcashbankid                  
    EXEC spReturnExRate @intCurrencyId, @strExRates,  @numTransEr output   
                   
    -- to take financialid FROM afinancialyear table with curfinancialyear=1 -- hari011211                  
    SELECT @intFinancialID = financialid FROM vwfinyearperiod WHERE @dtExDate 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 losposExchangeDetail, aItem                   
  WHERE sedExchangeId = @intexid and sedShopId = @intShopId and sedItemId = ItemId                   
  and (sedCostPrice = null or sedCostPrice = 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 hari 011213                  
    BEGIN                  
    -- to update the item rate to the gadCostPrice                     
    update losposExchangeDetail SET sedCostPrice = ItemRate             
     FROM aItem                   
     WHERE (sedCostPrice = null or sedCostPrice = 0) and                   
     sedExchangeId = @intexid and sedShopId = @intShopId and                   
     sedItemId = ItemId  
     end    
       
         select @NetSalesValueWTax=SUM(ToalAmount), @numTotalbillValue = SUM(TotalWithoutTax),@numtTaxExVal=SUM(TaxAmount) from (  
      select sedUnitPrice ToalAmount ,sedUnitPrice- isnull(sedItemTaxAmount,0) TotalWithoutTax,isnull(sedItemTaxAmount,0) TaxAmount from losposExchangeDetail where sedShopId = @intShopId and sedExchangeId  = @intexid                  
              and sedBillOrExchange = 'B' and sedexchangeqty > 0     
      union all                                  
      select -sedUnitPrice,-(sedUnitPrice- isnull(sedItemTaxAmount,0)) ,-isnull(sedItemTaxAmount,0)  from losposExchangeDetail where sedShopId = @intShopId  and sedExchangeId  = @intexid                  
                     and sedBillOrExchange = 'E'  )vw      
                
       set    @NetSalesValueWTaxTmp=@NetSalesValueWTax
              
           set @numreturncost=0.0 -- Ref 04             
     SELECT @numreturncost = isnull(sum(sedCostPrice * (sedExchangeQty + isnull(sedExcFreeQty,0))), 0)                  
      FROM losposExchangeDetail                  
      WHERE sedShopId = @intShopId and sedExchangeId  = @intexid                  
      and sedBillOrExchange = 'B' and sedexchangeqty>0                  
      group by sedShopId, sedExchangeId                  
      set @numNewitemcost=0.0--               
     SELECT @numNewitemcost = isnull(sum(sedCostPrice * (sedquantity + isnull(sedFreeQty,0))),0)                  
      FROM losposExchangeDetail                  
      WHERE sedShopId = @intShopId and sedExchangeId  = @intexid                  
      and sedBillOrExchange = 'E'                  
      group by sedShopId, sedExchangeId                  
                      
     SET @NetCost = abs(@numreturncost - @numNewitemcost)                  
                       
     SET @numTotalbillValue = isnull(@numtotalbillvalue,0)                  
     SET @numtotalexvalue = isnull(@numtotalexvalue,0)                  
     SET @numreturncost = isnull(@numreturncost,0)                  
     SET @numNewitemcost = isnull(@numNewitemcost,0)    
    
    INSERT INTO moaJournalHeader (JournalID, CompanyId, JournalDate,                   
       referenceno, remarks,financialID,Type, CurrencyId,chequedate, updatetime)                   
       VALUES                   
       (@intJournalID, @intCompanyId, @dtExDate, @strexNo,                   
       @strRemarks, @intFinancialID, 'EXC', @intComCurId,@dtExDate, @dtutime)    
         SET @intJournalDetailId = 1    
              
         if @NetSalesValueWTax> 0  --money out FROM cash box      
           begin  
           -- FOR converting the amount --->   
                          
		 --SELECT @intCurrencyId = CurrencyId FROM aAccountMaster WHERE AccountId = @intGoodsReturnAccId                        
		 --EXEC spReturnExRate @intCurrencyId, @strExRates,@numAccEr output                   
		 --EXEC spConvertCurrency @numTransEr, @numAccEr,@numTotalbillValue,@numAaccAmt output    
	       
		 set @NetSalesValueWTax=ABS(@NetSalesValueWTax)  
		 --set @numTotalbillValue=ABS(@numTotalbillValue) 		  
			-- debiting the goods return account                 
		 --- Ref 01                
	  
		  -- crediting cash  account     
		 SELECT @intCurrencyId = CurrencyId FROM aAccountMaster WHERE AccountId = @intCashBankId                        
		 EXEC spReturnExRate @intCurrencyId, @strExRates,@numAccEr output                   
		 EXEC spConvertCurrency @numTransEr, @numAccEr,@NetSalesValueWTax,@numAaccAmt output               
	      
	                        
	                
	                        
		 INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,                   
		 JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, departmentID,PostGroup)                  
		 VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,                   
		 @intCashBankId,  @NetSalesValueWTax * @NumEr,                   
		 @numAaccAmt, @NetSalesValueWTax * @depExRate, @intDepartmentID,null )   
		  SET @intJournalDetailId = @intJournalDetailId + 1     
	       
	        
     end      
    else --money in  FROM cash box     
        begin  
         -- debiting  cash  account   
			 set @NetSalesValueWTax=ABS(@NetSalesValueWTax)  
		 --set @numTotalbillValue=ABS(@numTotalbillValue)  
	       
		 SELECT @intCurrencyId = CurrencyId FROM aAccountMaster WHERE AccountId = @intCashBankId                        
		EXEC spReturnExRate @intCurrencyId, @strExRates,@numAccEr output                   
		EXEC spConvertCurrency @numTransEr, @numAccEr,@NetSalesValueWTax,@numAaccAmt output               
	                   
	                        
		 INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,                   
		 JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, departmentID,PostGroup)                  
		 VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 0,                   
		 @intCashBankId,  @NetSalesValueWTax * @NumEr,                   
		 @numAaccAmt, @NetSalesValueWTax * @depExRate, @intDepartmentID,null )   
		  SET @intJournalDetailId = @intJournalDetailId + 1     
		   -- crediting  slases  account  
		        
		         
	         
      end  
      
-----------------------------------------------------------------------------------------------------------
    if @numTotalbillValue> 0 
           begin 
           set @numTotalbillValue=ABS(@numTotalbillValue) 
           			 SELECT @intCurrencyId = CurrencyId FROM aAccountMaster WHERE AccountId = @intGoodsReturnAccId                        
				 EXEC spReturnExRate @intCurrencyId, @strExRates,@numAccEr output                   
				 EXEC spConvertCurrency @numTransEr, @numAccEr,@numTotalbillValue,@numAaccAmt output
				
		    			  INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,                   
			  JournalCrEDit, AccountId, Amount, ActualAmount,                  
			  DepAmount, departmentID,PostGroup)                  
			  VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 0,                   
			  @intGoodsReturnAccId, @numTotalbillValue * @NumEr,                   
			  @numAaccAmt,                   
			  @numTotalbillValue * @depExRate,                  
			  @intDepartmentID,null)                  
			 SET @intJournalDetailId = @intJournalDetailId + 1  
			 
           end
      
      else
      
      begin
      set @numTotalbillValue=ABS(@numTotalbillValue) 
       SELECT @intCurrencyId = CurrencyId FROM aAccountMaster WHERE AccountId = @intSalesAccountId                  
		   EXEC spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                  
		   EXEC spConvertCurrency @numTransEr, @numAccEr, @numTotalbillValue, @numAaccAmt output   
	         
		 --  SET @intJournalDetailId = @intJournalDetailId + 1     
	         
		INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,                   
		  JournalCrEDit, AccountId, Amount, actualAmount, DepAmount, departmentID,PostGroup)                  
		  VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,                   
		  @intSalesAccountId,  @numTotalbillValue * @NumEr,                   
		  @numAAccAmt,                   
		  @numTotalbillValue * @depExRate, @intDepartmentID,null)     
	        
		 SET @intJournalDetailId = @intJournalDetailId + 1   
      end
-------------------------------------------tax account posting---------------------------------------------------------------  
        DECLARE exTaxOUTcur CURSOR FOR                     
      select TaxAccountId ,sum(sedItemTaxAmount) sedItemTaxAmount   from (                   
     SELECT TaxAccountId,sum(isnull(sedItemTaxAmount,0)) sedItemTaxAmount FROM losposExchangeDetail,aTaxCategoryMaster                      
     WHERE sedShopId = @intShopId and sedExchangeId = @intexid and sedBillOrExchange = 'E'                   
     and sedItemTaxCategory = TaxId and  isnull(sedUnitPrice,0)>0   group by TaxAccountId  
     union  all
     SELECT TaxAccountId,-sum(isnull(sedItemTaxAmount,0)) sedItemTaxAmount FROM losposExchangeDetail,aTaxCategoryMaster                      
     WHERE sedShopId = @intShopId and sedExchangeId = @intexid and sedBillOrExchange = 'B'                   
     and sedItemTaxCategory = TaxId and  isnull(sedUnitPrice,0)>0 and isnull(sedexchangeqty,0) > 0 group by TaxAccountId      ) vw    group by   TaxAccountId   
                    
    OPEN exTaxOUTcur                    
                     
    FETCH NEXT FROM exTaxOUTcur INTO @intOutPutTaxAccount,@intOutPutTaxAmount                  
                       
    WHILE @@Fetch_status = 0                    
    BEGIN                  
              
     if @intOutPutTaxAmount<0   
		  begin  
			  set @intJournalType=0    
			  set @intOutPutTaxAmount =abs( @intOutPutTaxAmount)   
		  end  
			else  
				 begin  
				 
			  set @intJournalType=1   
			  --if @NetSalesValueWTaxTmp < 0 
			  --begin
			  -- set @intJournalType=0   
			  --end
			  
		  end  
    
                      
    EXEC spConvertCurrency @numTransEr, @numAccEr,@intOutPutTaxAmount,@numAaccAmt output     
      
      
                     
                         
     INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,                     
     JournalCrEDit, AccountId, Amount, ActualAmount,                    
     DepAmount, departmentID,PostGroup)                    
     VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, @intJournalType,                     
     @intOutPutTaxAccount, @intOutPutTaxAmount * @NumEr,                     
     @numAaccAmt,                     
     @intOutPutTaxAmount * @depExRate,                    
     @intDepartmentID,null)                   
                          
    SET @intJournalDetailId = @intJournalDetailId + 1                   
     FETCH NEXT FROM exTaxOUTcur INTO @intOutPutTaxAccount,@intOutPutTaxAmount                  
    END                    
    --                  
                     
   Close exTaxOUTcur                    
   Deallocate exTaxOUTcur             
                           
-----------------------------inventoryPosting------------------------------------------------------------                       
                              
  
      
       IF @numNewitemcost > @numreturncost                  
    -- debiting inventory value IF the net effect of exchange increases stock value                  
    BEGIN                  
                   
     -- FOR CONVERTING AMOUNT --->                  
     SELECT @intCurrencyId = CurrencyId                   
      FROM aAccountMaster                  
      WHERE AccountId = @intINVentoryAccID                  
                    
     EXEC spReturnExRate @intCurrencyId, @strExRates,                   
         @numAccEr output                   
                       
     EXEC spConvertCurrency @numTransEr, @numAccEr,                   
       @NetCost,                   
       @numAaccAmt output                  
              
                  
     -- crediting inventory value                  
     INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,                   
      JournalCrEDit, AccountId, Amount, actualAmount, DepAmount, departmentID,PostGroup)                  
      VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,                   
      @intInventoryaccid,  @NetCost * @NumEr,                   
      @numAaccAmt,                   
      @NetCost * @DepExRate, @intDepartmentID,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,                   
      @NetCost, @numAaccAmt output                  
                  
     -- debiting cost of goods sold account                  
     INSERT INTO moaJournalDetails (JournalID,                   
      JournalDetailId, CompanyId,                   
      JournalCrEDit, AccountId, Amount, actualAmount,                   
      DepAmount, departmentID,PostGroup)                  
      VALUES (@intJournalID, @intJournalDetailId,                   
      @intCompanyId, 0,                   
      @intCostOfGoodsAccId,                    
      @NetCost * @numEr ,                   
      @numAaccAmt,                   
      @NetCost * @depExRate,                  
      @intDepartmentID,4)                  
                     
    END                  
                  
    IF @numNewitemcost < @numreturncost                  
    -- crediting inventory value IF the net effect of exchange increases stock value                  
    BEGIN                  
     -- FOR CONVERTING AMOUNT --->                  
     SELECT @intCurrencyId = CurrencyId                   
      FROM aAccountMaster                  
      WHERE AccountId = @intINVentoryAccID                      
                  
     EXEC spReturnExRate @intCurrencyId, @strExRates, @numAccEr output                   
                       
     EXEC spConvertCurrency @numTransEr, @numAccEr, @NetCost,                   
        @numAaccAmt output                  
                  
     -- debiting  inventory account                  
     INSERT INTO moaJournalDetails (JournalId, JournalDetailId, CompanyId,                   
      JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, departmentID,PostGroup)                  
      VALUES (@intJournalId, @intJournalDetailId, @intCompanyId, 0,                   
      @intInventoryaccid,  @NetCost * @numEr,                   
      @numAaccAmt,                   
      @NetCost * @depExRate,                  
      @intDepartmentID,2)                  
                  
     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,                   
      @NetCost, @numAaccAmt output                  
                  
     -- crediting cost of goods sold account                  
     INSERT INTO moaJournalDetails (JournalID, JournalDetailId, CompanyId,                   
      JournalCrEDit, AccountId, Amount, ActualAmount, DepAmount, DepartmentID,PostGroup)                  
      VALUES (@intJournalID, @intJournalDetailId, @intCompanyId, 1,                   
      @intCostOfGoodsAccId,  @NetCost * @numEr,                   
      @numAaccAmt, @NetCost * @depExRate, @intDepartmentID,2)                  
                  
    END                                
                  
    -- mark the record AS postED                   
   update losposExchangeHeader SET sehpostED =1 WHERE sehCompanyId = @intCompanyId                   
    and sehShopId = @intShopId and sehExchangeId = @intexid                    
                      
   SET @intJournalID = @intJournalID + 1                  
   SET @numTotalbillValue = 0.00                  
   SET @numtotalexvalue = 0.00                  
   SET @numNewitemcost = 0.00                   
   SET @numreturncost = 0.00       
    
  FETCH NEXT FROM excur INTO @intexid, @strexno, @dtExDate, @strremarks,                   
    @intsalesAccountId, @intCashBankId, @NumEr, @dtutime, @intDepartmentid,                  
    @depExRate, @strExRates 
    
  end      
    
                   
                
 Close excur                  
 Deallocate excur    
 end


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

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

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spMag_GetShopItemPrice]    Script Date: 10/12/2012 11:59:44 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
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,1,'155,156',0,'',0,0,0   
----------------------------------------------------------------------   
--REF.NO:2
--MODIFIED BY : Sujith,MANUNADH.U
--MODIFIED ON : 12/10/2012    
--COMMENTS	  : To solve the issue while taking item price list report in by select two categories
--spMag_GetShopItemPrice 1,1,1,'3,1',0,'',0,0  
----------------------------------------------------------------------   
CREATE proc [dbo].[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,ItemCategoryID
	)    
	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 ,ItemCategoryID   
		FROM ashopitemdetail asd    
			INNER JOIN vwShopItemStockitemsItemDtls vsd ON asd.itemid = vsd.ItemID    
				AND (asd.shopid=@IntShopId OR @IntShopId=0) 
				--<<REF.NO:2>>Old code is commented and add new 
				--AND (ItemCategoryID in (@strItemCate) OR @strItemCate='')--<<Old>>
				AND (
					ItemCategoryID in (select convert(int,cid) from dbo.fnSplit(@strItemCate,',')) 
					OR @strItemCate=''
				)
				--<<REF.NO:2>>
				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 c.*,CategoryNameDescription from cteShopItems c 
		inner join aItemCategory a on c.ItemCategoryID=a.ItemCategoryID  
	where selectORder=1 ORder by shopname    
SET NOCOUNT OFF    
END    
-------------------------------------
GO

GO
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
--Ticket/Task ID:QWO-643922
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
GO

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spDebtorAgeSum]    Script Date: 09/20/2012 10:06:26 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[spDebtorAgeSum]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[spDebtorAgeSum]
GO

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spDebtorAgeSum]    Script Date: 09/20/2012 10:06:26 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- Procedure  
-- Modified by   : Kishore  
-- Modified on  : 10/06/2003  
-- Comments  : Added the Having condition in each select query  
--                        (on comparison with v2)  
-----------------------------------------------------------------------------  
-- Modified by   : venki, Hariharan R  
-- Modified on  : 11/09/2003 ....240903 (added debtoraccid ), 08/01/2004  
-- Comments  : given isnull --then 0 for settledamt field  
--                        (on comparison with v2)  
-- Modified by   : venkitesh  
-- Modified on  : 11/09/2003 ....240903 (added debtoraccid )  
-- Comments  : given vwSettlements as derived table filtering customerid, depid and invoicedate  
-- Modified by   : venkitesh  , Hariharan  
-- Modified on  : 29/06/2004, 08/12/2004  
-- Comments  : Corrected ageing and due period basis of todate  
--           : Corrected the company wise report fetching removing departmentid condition on settlements query  
-----------------------------------------------------------------------------  
-- RefNo-1  
-- Modified by : Regin  
-- Modified on : 16-06-2010  
-- Comments    : To speed up the execution.  
-- Old technique had below tow steps:  
--   1. Fetch ALL rows of vwInvoices and vwsettlements  
--      into #tempvwInvoices and #tempvwsettlements respectively.  
--      Since all rows are fetched, it took huge time to complete.  
--   2. Required rows were fetched from #tempvwInvoices  
--      and #tempvwsettlements applying condition.  
-- New technique eliminates the temporary tables and has one step:  
--   1. Required rows are fetched direcly from vwInvoices  
--      and vwsettlements applying condition.  
--      Since rows are fetched on condition, fetch completes quickly.  
-- Time taken to generate the outstanding invoices report for one customer  
-- in Simdi DB is...  
--   In old technique: 3 Minues  
--   In new technique: 20 Seconds  
-----------------------------------------------------------------------------  
--RefNo:01  
--Modified By : VinothMurugan V.  
--Modified On : 06/08/2010  
--Purpose     : Adding Currencyid  
--------------------------------------------------------------------------  
--Modified By : SHINE  
--Modified On : 28/07/2011  
--Purpose     : When added to VSS some unwaned comments came. So removed it  
--  spdebtoragesum '20010101','20100805','',0,0,0,'',''  
--RefNo:02  
--Modified By : Jyothish.SR.  
-- Modified On : 27/03/2012  
--Purpose     : select *  statement is avoid in vwsettlements and vwinvinvoices  
-----------------------------------------------------------------------------  
--RefNo:03  
--Modified By : MANU
--Modified On : 25/08/2012  
--Purpose     : Adding SalesPersonName to show in the Outstanding Invoice report 
--------------------------------------------------------------------------
--RefNo:04 
--Modified By : BIJESH.B
--Modified On : 12/10/2012  
--Ticket id   : QWO-643922
--Purpose     : Added '@intSalesPersonID' parameter to show in the Outstanding Invoice report 
--              based on selected Sales Person.
----------------------------------------------------------------------------
-- exec spdebtoragesum '20080801','20080901','',0,0,0,'','',0

create PROCEDURE dbo.spDebtorAgeSum (  
	@dtstartdate varchar(11),@dtinvdate as varchar(11),@intcustid varchar(1000),@intdepartid int,
	@intageTodate int=0 ,@intShopID int=0,@strCatName as Varchar(30)='', 
	@strGroupName as Varchar(30)='', @intSalesPersonID int=0  
)  
as  
begin  
	declare @strquery as nvarchar(4000)  
	declare @SettleCustId as varchar(1500), @Invcustid as varchar(1500)  
	declare @strShop as nvarchar(4000)  
	declare  @strCatCond as Varchar(300)  
	declare @strGroupCond as Varchar(300),@strSalesPersonID as nvarchar(10) 
	
	set  @strSalesPersonID = convert(nvarchar(50),@intSalesPersonID)
	 
	SET @SettleCustId = ''  
	set @Invcustid = ''  
	set @strShop = ''  
	set @strCatCond=''  
	set @strGroupCond=''  
	Create table #tmpInvoices (
		CompanyID int,shopid int,DepartmentID int,InvoiceID int,customerid int,invoicedate datetime,  
		invoiceno varchar(50),Referenceno varchar (100),remarks varchar(1000),InvAmt numeric(18,2),  
		Due varchar(7),Type varchar(7),Debtortype varchar(50),updatetime datetime,  
		CustomerCategory varchar(100),duedate datetime ,depexrate numeric(18,2),InterFaceID int ,  
		SalesPersonID int,CustomerType char(1),DutyAmt numeric(18,2),CostPrice numeric(18,4),  
		CustGroupName varchar(100), TaxAmount numeric (18,2),age int  
	)  
	Create Table #tmpSettlements( 
		customerid int,ReceiptNo varchar(50),companyid int,invoiceid int,shopid int,settleddate datetime,  
		departmentid int,settledamt numeric(18,2),Type varchar(50)
	)  
	-- Commented (RefNo-1)  
	-- select * into #tempvwInvoices from vwInvoices  
	-- select * into #tempvwsettlements from vwsettlements  
	if @strCatName<>''  
		begin  
			set @strCatCond = ' CustomerCategory = ''' + @strCatName + ''' And '  
		end  
	if @strGroupName<>''  
		begin  
			set @strGroupCond = ' CustGroupName = ''' + @strGroupName + ''' And '  
		end  
	if @intShopID > 0  
		Begin  
			set @strShop=' And  #tmpInvoices.shopid = ' + cast(@intShopID As varchar)  
		end  
	if @intcustid<>''    --hari given to handle with out customerid also  
		Begin  
			set @SettleCustId = ' customerid in (' + @intcustid + ') and'  
			set @Invcustid = 'vwInvoices.customerid in (' + @intcustid + ') and'  
		End  
	-- if @dtstartdate =''  
	-- Begin  
	--    if @intdepartid >0  
	--    set @strquery ='insert #tmpInvoices  
	--     Select *,0 from #tempvwInvoices vwInvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
	--     ' invoicedate <=''' + @dtinvdate + '''' +  
	--     ' and departmentid = ' + cast(@intdepartid as varchar)  
	--    else  
	--     set @strquery ='insert #tmpInvoices  
	--     Select *,0 from #tempvwInvoices vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
	--     ' invoicedate <=''' + @dtinvdate + ''''  
	--    End  
	-- Else  
	-- Begin  
	--  if @intdepartid >0  
	--     set @strquery ='insert #tmpInvoices  
	--     Select *,0 from #tempvwInvoices vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
	--     ' invoicedate <=''' + @dtinvdate + '''' +  
	--     ' and departmentid = ' + cast(@intdepartid as varchar) +  
	--     ' and invoicedate >=''' + @dtstartdate + ''''  
	--  else  
	--   set @strquery ='insert #tmpInvoices  
	--   Select *,0 from #tempvwInvoices vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
	--      ' invoicedate <=''' + @dtinvdate + '' +  
	--   ''' and invoicedate >=''' + @dtstartdate + ''''  
	-- End  
	-- Instead of selecting from #tempvwInvoices,  
	-- required rows are fetched direcly from vwInvoices applying condition.  
	-- Thus increasing speed. Old code commented above. (RefNo-1)  
	if @dtstartdate =''  
		Begin  
			if @intdepartid >0  
				--RefNo:02  
				set @strquery ='insert #tmpInvoices  
					Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,
					Referenceno,remarks,InvAmt,Due,Type,Debtortype,updatetime,CustomerCategory,duedate,
					depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,CostPrice,CustGroupName,
					TaxAmount,0 from vwInvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
					' invoicedate <=''' + @dtinvdate + '''' +  
					' and departmentid = ' + cast(@intdepartid as varchar)  
			else  
				--   RefNo:02  
				set @strquery ='insert #tmpInvoices 
					Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,
					Referenceno,remarks,InvAmt,Due,Type,Debtortype,updatetime,CustomerCategory,duedate,
					depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,CostPrice,CustGroupName,
					TaxAmount ,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
					' invoicedate <=''' + @dtinvdate + ''''  
		End  
	Else  
		Begin  
			if @intdepartid >0  
				set @strquery ='insert #tmpInvoices  
					Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,
					Referenceno,remarks,InvAmt,Due,Type,Debtortype,updatetime,CustomerCategory,duedate,
					depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,CostPrice,CustGroupName,
					TaxAmount ,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
					' invoicedate <=''' + @dtinvdate + '''' + ' and departmentid = ' + 
					cast(@intdepartid as varchar) + ' and invoicedate >=''' + @dtstartdate + ''''  
			else  
				set @strquery ='insert #tmpInvoices  
					Select CompanyID,shopid,DepartmentID,InvoiceID,customerid,invoicedate,invoiceno,
					Referenceno,remarks,InvAmt,Due,Type,Debtortype,updatetime,CustomerCategory,duedate,
					depexrate,InterFaceID,SalesPersonID,CustomerType,DutyAmt,CostPrice,CustGroupName,
					TaxAmount ,0 from vwinvoices where ' + @Invcustid + @strCatCond + @strGroupCond +  
					' invoicedate <=''' + @dtinvdate + '' + ''' and invoicedate >=''' + @dtstartdate + ''''  
		End  
	exec sp_Executesql @strquery  
	--  if @dtstartdate =''  
	--  Begin  
	--  if @intdepartid >0  
	--   set @strquery  = ' insert #tmpSettlements Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +  
	--   ' departmentid = ' + cast(@intdepartid as varchar) +  
	--   ' and settleddate <=''' + @dtinvdate +  ''''  
	--  else  
	--   set @strquery  = 'insert #tmpSettlements  Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +  
	--      ' settleddate <=''' + @dtinvdate + ''''  
	--  
	--  End  
	--    Else  
	--    Begin  
	--  if @intdepartid >0  
	--   set @strquery  = ' insert #tmpSettlements Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +  
	--      ' departmentid = ' + cast(@intdepartid as varchar) +  
	--   ' and settleddate <=''' + @dtinvdate +  '' +  
	--   ''' and settleddate >=''' + @dtstartdate + ''''  
	--   else  
	--   set @strquery  = 'insert #tmpSettlements  Select * from #tempvwsettlements vwsettlements where ' + @SettleCustId +  
	--      ' settleddate <=''' + @dtinvdate + '' +  
	--   ''' and settleddate >=''' + @dtstartdate + ''''  
	--  
	--   End  
	-- Instead of selecting from #tempvwsettlements,  
	-- required rows are fetched direcly from vwsettlements applying condition.  
	-- Thus increasing speed. Old code commented above. (RefNo-1)  
	
	
	if @dtstartdate =''  
		Begin  
			if @intdepartid >0  
				--RefNo:02  
				set @strquery  = ' insert #tmpSettlements Select customerid,ReceiptNo,companyid,
					invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where 
					' + @SettleCustId +  ' departmentid = ' + cast(@intdepartid as varchar) +  
					' and settleddate <=''' + @dtinvdate +  ''''  
			else                             
				set @strquery  = 'insert #tmpSettlements  Select customerid,ReceiptNo,companyid,
					invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where ' 
					+ @SettleCustId + ' settleddate <=''' + @dtinvdate + ''''  
		End  
	Else  
		Begin  
			if @intdepartid >0  
				set @strquery  = ' insert #tmpSettlements Select customerid,ReceiptNo,companyid,
					invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where 
					' + @SettleCustId +  ' departmentid = ' + cast(@intdepartid as varchar) +  
					' and settleddate <=''' + @dtinvdate +  '' +  ''' and settleddate >=''' + 
					@dtstartdate + ''''  
			else  
				--   RefNo:02  
				set @strquery  = 'insert #tmpSettlements Select customerid,ReceiptNo,companyid,
					invoiceid,shopid,settleddate,departmentid,settledamt,Type from vwsettlements where 
					' + @SettleCustId + ' settleddate <=''' + @dtinvdate + '' +  
					''' and settleddate >=''' + @dtstartdate + ''''  
		End		
	
	
	exec sp_Executesql @strquery  
	-----RefNo:01  
	
	--<<RefNo:03 >> Comment the previous query and add new
	--<<Old Query>>
	--set @strquery = 'SELECT  max(invamt) invamt,isnull(sum(settledamt),0) settleamt,
	--	#tmpInvoices.invoiceid,#tmpInvoices.customerid,#tmpInvoices.shopid,#tmpInvoices.due,
	--	#tmpInvoices.invoicedate,#tmpInvoices.invoiceno,#tmpInvoices.type,remarks,customername,
	--	currencyname,symbol, #tmpInvoices.duedate,datediff(dd,#tmpInvoices.duedate, ''' + @dtinvdate + 
	--	''' ) overduedays, address1, address2, address3,#tmpInvoices.referenceno,debtoraccid,
	--	b.accountdesc, aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID FROM  
	--	#tmpInvoices #tmpInvoices LEFT OUTER JOIN #tmpSettlements vwsettlements ON 
	--	#tmpInvoices.customerid = vwsettlements.customerid AND  #tmpInvoices.CompanyID = 
	--	vwsettlements.companyid AND  #tmpInvoices.InvoiceID = vwsettlements.invoiceid AND  
	--	#tmpInvoices.type = vwsettlements.type AND  #tmpInvoices.shopid = vwsettlements.shopid  and  
	--	(vwsettlements.settleddate<=''' + @dtinvdate + ''' or vwsettlements.settleddate is null),  
	--	aCurrencyMaster,aCustomerMaster,aAccountMaster b WHERE #tmpInvoices.customerid = 
	--	aCustomerMaster.CustomerID AND  #tmpInvoices.CompanyID = aCustomerMaster.CompanyID and  
	--	aCustomerMaster.CurrencyID = aCurrencyMaster.CurrencyID AND aCustomerMaster.CompanyID = 
	--	aCurrencyMaster.CompanyID and  aCustomerMaster.debtorAccID = b.AccountID ' + @strShop  + '  
	--	and  #tmpInvoices.invoicedate<=''' + @dtinvdate + '''  group by #tmpInvoices.invoiceid,
	--	#tmpInvoices.departmentid,#tmpInvoices.customerid, #tmpInvoices.shopid,due ,invoicedate,  
	--	invoiceno,#tmpInvoices.type,remarks,customername,currencyname,symbol,#tmpInvoices.duedate,  
	--	address1, address2, address3, #tmpInvoices.referenceno,debtoraccid,b.AccountDesc ,
	--	aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID  
	--	having max(invamt) <> sum(isnull(settledamt,0))'  
	--<<Old Query>>

--RefNo:04 start commented below and added	
	----<<New Query>>
	--set @strquery = 'SELECT  max(invamt) invamt,isnull(sum(settledamt),0) settleamt,
	--	#tmpInvoices.invoiceid,#tmpInvoices.customerid,#tmpInvoices.shopid,#tmpInvoices.due,
	--	#tmpInvoices.invoicedate,#tmpInvoices.invoiceno,#tmpInvoices.type,remarks,customername,
	--	currencyname,symbol, #tmpInvoices.duedate,datediff(dd,#tmpInvoices.duedate, ''' + @dtinvdate + 
	--	''' ) overduedays, address1, address2, address3,#tmpInvoices.referenceno,debtoraccid,
	--	b.accountdesc, aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID 
	--	,isnull(sp.Spername,'''')SalesPerson
	--	FROM  #tmpInvoices #tmpInvoices LEFT OUTER JOIN #tmpSettlements vwsettlements ON 
	--	#tmpInvoices.customerid = vwsettlements.customerid AND  #tmpInvoices.CompanyID = 
	--	vwsettlements.companyid AND  #tmpInvoices.InvoiceID = vwsettlements.invoiceid AND  
	--	#tmpInvoices.type = vwsettlements.type AND  #tmpInvoices.shopid = vwsettlements.shopid  and  
	--	(vwsettlements.settleddate<=''' + @dtinvdate + ''' or vwsettlements.settleddate is null)
	--	left outer join		 sp on sp.Sperid=isnull(#tmpInvoices.SalesPersonID,0),  
	--	aCurrencyMaster,aCustomerMaster,aAccountMaster b WHERE #tmpInvoices.customerid = 
	--	aCustomerMaster.CustomerID AND  #tmpInvoices.CompanyID = aCustomerMaster.CompanyID and  
	--	aCustomerMaster.CurrencyID = aCurrencyMaster.CurrencyID AND aCustomerMaster.CompanyID = 
	--	aCurrencyMaster.CompanyID and  aCustomerMaster.debtorAccID = b.AccountID ' + @strShop  + '  
	--	and  #tmpInvoices.invoicedate<=''' + @dtinvdate + '''  group by #tmpInvoices.invoiceid,
	--	#tmpInvoices.departmentid,#tmpInvoices.customerid, #tmpInvoices.shopid,due ,invoicedate,  
	--	invoiceno,#tmpInvoices.type,remarks,customername,currencyname,symbol,#tmpInvoices.duedate,  
	--	address1, address2, address3, #tmpInvoices.referenceno,debtoraccid,b.AccountDesc ,
	--	aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID  
	--	,sp.Spername
	--	having max(invamt) <> sum(isnull(settledamt,0))'  
	----<<New Query>>

if @intSalesPersonID=0 
begin
	
	set @strquery = 'SELECT  max(invamt) invamt,isnull(sum(settledamt),0) settleamt,
		#tmpInvoices.invoiceid,#tmpInvoices.customerid,#tmpInvoices.shopid,#tmpInvoices.due,
		#tmpInvoices.invoicedate,#tmpInvoices.invoiceno,#tmpInvoices.type,remarks,customername,
		currencyname,symbol, #tmpInvoices.duedate,datediff(dd,#tmpInvoices.duedate, ''' + @dtinvdate + 
		''' ) overduedays, address1, address2, address3,#tmpInvoices.referenceno,debtoraccid,
		b.accountdesc, aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID 
		,isnull(sp.Spername,'''')SalesPerson
		FROM  #tmpInvoices #tmpInvoices LEFT OUTER JOIN #tmpSettlements vwsettlements ON 
		#tmpInvoices.customerid = vwsettlements.customerid AND  #tmpInvoices.CompanyID = 
		vwsettlements.companyid AND  #tmpInvoices.InvoiceID = vwsettlements.invoiceid AND  
		#tmpInvoices.type = vwsettlements.type AND  #tmpInvoices.shopid = vwsettlements.shopid  and  
		(vwsettlements.settleddate<=''' + @dtinvdate + ''' or vwsettlements.settleddate is null)
		left outer join AsalesPersonmaster sp on sp.Sperid=isnull(#tmpInvoices.SalesPersonID,0),  
		aCurrencyMaster,aCustomerMaster,aAccountMaster b WHERE #tmpInvoices.customerid = 
		aCustomerMaster.CustomerID AND  #tmpInvoices.CompanyID = aCustomerMaster.CompanyID and  
		aCustomerMaster.CurrencyID = aCurrencyMaster.CurrencyID AND aCustomerMaster.CompanyID = 
		aCurrencyMaster.CompanyID and  aCustomerMaster.debtorAccID = b.AccountID ' + @strShop  + '  
		and  #tmpInvoices.invoicedate<=''' + @dtinvdate + '''  group by #tmpInvoices.invoiceid,
		#tmpInvoices.departmentid,#tmpInvoices.customerid, #tmpInvoices.shopid,due ,invoicedate,  
		invoiceno,#tmpInvoices.type,remarks,customername,currencyname,symbol,#tmpInvoices.duedate,  
		address1, address2, address3, #tmpInvoices.referenceno,debtoraccid,b.AccountDesc ,
		aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID  
		,sp.Spername
		having max(invamt) <> sum(isnull(settledamt,0))'  
		
	end

else
	begin

	set @strquery = 'SELECT  max(invamt) invamt,isnull(sum(settledamt),0) settleamt,
		#tmpInvoices.invoiceid,#tmpInvoices.customerid,#tmpInvoices.shopid,#tmpInvoices.due,
		#tmpInvoices.invoicedate,#tmpInvoices.invoiceno,#tmpInvoices.type,remarks,customername,
		currencyname,symbol, #tmpInvoices.duedate,datediff(dd,#tmpInvoices.duedate, ''' + @dtinvdate + 
		''' ) overduedays, address1, address2, address3,#tmpInvoices.referenceno,debtoraccid,
		b.accountdesc, aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID 
		,isnull(sp.Spername,'''')SalesPerson
		FROM  #tmpInvoices #tmpInvoices LEFT OUTER JOIN #tmpSettlements vwsettlements ON 
		#tmpInvoices.customerid = vwsettlements.customerid AND  #tmpInvoices.CompanyID = 
		vwsettlements.companyid AND  #tmpInvoices.InvoiceID = vwsettlements.invoiceid AND  
		#tmpInvoices.type = vwsettlements.type AND  #tmpInvoices.shopid = vwsettlements.shopid  and  
		(vwsettlements.settleddate<=''' + @dtinvdate + ''' or vwsettlements.settleddate is null)
		left outer join	AsalesPersonmaster sp on sp.Sperid=isnull(#tmpInvoices.SalesPersonID,0),  
		aCurrencyMaster,aCustomerMaster,aAccountMaster b WHERE #tmpInvoices.customerid = 
		aCustomerMaster.CustomerID AND  #tmpInvoices.CompanyID = aCustomerMaster.CompanyID and  
		aCustomerMaster.CurrencyID = aCurrencyMaster.CurrencyID AND aCustomerMaster.CompanyID = 
		aCurrencyMaster.CompanyID and  aCustomerMaster.debtorAccID = b.AccountID ' + @strShop  + '  
		and  #tmpInvoices.invoicedate<=''' + @dtinvdate + ''' and #tmpInvoices.SalesPersonID=' +
		@strSalesPersonID + ' group by #tmpInvoices.invoiceid,
		#tmpInvoices.departmentid,#tmpInvoices.customerid, #tmpInvoices.shopid,due ,invoicedate,  
		invoiceno,#tmpInvoices.type,remarks,customername,currencyname,symbol,#tmpInvoices.duedate,  
		address1, address2, address3, #tmpInvoices.referenceno,debtoraccid,b.AccountDesc ,
		aCustomerMaster.CustomerCategory,aCurrencyMaster.CurrencyID  
		,sp.Spername
		having max(invamt) <> sum(isnull(settledamt,0))'
end	
	
	
--RefNo:04 ends
	if @intageTodate=1  
		begin  
			update #tmpInvoices set age=datediff(day,invoicedate,CONVERT(DATETIME, @dtinvdate,102))  
			update #tmpInvoices set due =  case when (age  >=0 and age <= 30) then '0 - 30'  
				when (age  >=31 and age <= 60)  then '31 - 60'  
				when (age  >=61 and age <= 90) then '61 - 90'  
				when (age  >=91) then ' > 90' else '' end  
		end  
	
	exec sp_Executesql @strquery  
	
--select * from #tempvwsettlements  
-- Commented (RefNo-1)  
-- drop table #tempvwInvoices  
-- drop table #tempvwsettlements  

drop table #tmpInvoices  
drop table #tmpSettlements  
end
go

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

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

USE [adminv2]
GO

/****** Object:  StoredProcedure [dbo].[spULBusinessPromotion]    Script Date: 10/12/2012 17:04:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

  
--exec spULBusinessPromotion 1,2      
--Created on   : 10/09/2008              
--Created by  : Prasanth Joseph              
--Comments  : For Posting Business Promotions Transactions     
--RefNo1: Added by MANUNADH.U on 03.06.2011 for the Ticket: ZES-242125     
--to post only confirmed BusinessPromotion             
---------------------------------------------------------------------              
--RefNO       : RefNo-2  
--Modified By : Bijesh.B  
--Modified on : 14/02/2012  
--Purpose     : No need to post Business Promotion transaction if Business Promotion  
--              A/c is null in package settings  
---------------------------------------------------------------------   
--RefNO       : RefNo-3
--Modified By : MANU
--Modified on : 12/10/2012  
--Purpose     : To solve the issue :While posting the business promotion, if its quantity 
--is less than 1, it is posting to the ledger as zero.  
--Solution	  : Increase the precision of @numTotatRecAmount,@numBPAmt from NumEric(18,2) to NumEric(18,8) 
--------------------------------------------------------------------- 
 --spULBusinessPromotion 1,1 
CREATE proc [dbo].[spULBusinessPromotion]             
	@intCompanyID as int,@intShopId as int               
as               
begin              
	Declare @intJournalId as int,@intJournalDetailId as int,@intFinancialID as int,@intReceiptId as int,
		@intCustomerId as int,@intDepartmentID as int,@intComCurID as int,@intinventoryaccid as int,
		@intBPAcc as int,@intcomdeptid as int,@intCurrencyId as int,@intCustomerAccID as int,                                     
		@numTotatRecAmount as NumEric(18,8),@strReceipteNo as varchar(50),@strRemarks as varchar(250),
		@dtReceiptDate as datetime,@dtutime as datetime ,@numBPAmt as numeric(18,8) --RefNo1   
           
	/* 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 @numTotatRecAmount  = 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 @intBPAcc =BusinessPromotionAcc,@intinventoryaccid=InventoryID                   
	from apackagesettings  where companyid = @intcompanyid              
   
	if isnull(@intBPAcc,0)<>0     --RefNo-2  if condition added  
		begin  
			set @intJournalId = @intJournalId + 1              
			            
			Declare invcur cursor for         
			   
			SELECT wchID,wchNo,wchDate,null,wchRemarks,wchFinancialID,wchUpdatedTime,wchAmount      
			FROM losWarrentyClaimHeader      
			WHERE wchType='BP' and wchShopid= @intShopId and wchCompanyID=@intCompanyID      
				and wchposted=0 and wchCancelled=0  and wchConfirmed=1 --RefNo1    
			             
			open invcur              
			            
			fetch next FROM invcur into @intReceiptId, @strReceipteNo, @dtReceiptDate, @intCustomerId,        
				@strremarks,@intfinancialid, @dtutime, @numTotatRecAmount             
			while @@Fetch_status = 0              
			begin              
				insert into moaJournalHeader (JournalId, CompanyID, JournalDate, referenceno, remarks,     
					financialID,Type, CurrencyId, chequedate, updatetime)               
				values (@intJournalId, @intCompanyID, @dtReceiptDate, @strReceipteNo,               
					@strRemarks, @intFinancialID,'BP', @intcomCurID,@dtReceiptDate, @dtutime)              
				--HPSDP=Hire Purchase Shop Down Payment           
				set @intJournalDetailId = 1               

				--===========================================================================RefNo1  
				-- getting the total amount with qty and item cost price    
				select @numBPAmt = isnull(sum(wcdQty * wcdCostPrice),0)     
				from losWarrentyClaimDetail     
				where wcdShopID = @intShopId and wcdID = @intReceiptId    
				      
				--===========================================================================RefNo1      
				/* 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,@intinventoryaccid, @numBPAmt,               
					@numBPAmt,@intDepartmentID,@numBPAmt, 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, @intBPAcc,               
					@numBPAmt, @numBPAmt,@intDepartmentID, @numBPAmt, 1)        

				UPDATE losWarrentyClaimHeader  set wchPosted=1       
				WHERE wchShopID=@intShopId and wchCompanyID=@intCompanyID         
					and wchType='BP' and wchID=@intReceiptId         

				set @intJournalId = @intJournalId + 1              
	             
				fetch next FROM invcur into @intReceiptId, @strReceipteNo, @dtReceiptDate, @intCustomerId,        
				@strremarks,@intfinancialid, @dtutime, @numTotatRecAmount               
			end              
		Close invcur              
		Deallocate invcur              
	end  
end   
  
GO




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












